XML 文本提取 [英] XML text extraction
问题描述
场景:
给定以下 XML 文件:
Given the following XML file:
<a:root
xmlns:h="http://www.w3.org/TR/html4/"
xmlns:f="http://www.w3schools.com/furniture">
<h:table>
<h:tr>
<h:td>Apples</h:td>
<h:td>Bananas</h:td>
</h:tr>
</h:table>
<f:table>
<f:name>African Coffee Table</f:name>
<f:width>80</f:width>
<f:length>120</f:length>
</f:table>
aaaaaaaaaaaaaa
</a:root>
如何提取主元素内的文本
:
How do I extract the text inside the main element <a:root>
:
"\naaaaaaaaaaaaaa\n"
我现在拥有的代码是:
import java.io.File;
import java.util.Stack;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
public class Proof {
public static void main(String[] args) {
Document doc = null;
DocumentBuilderFactory dbf = null;
DocumentBuilder docBuild = null;
try {
dbf = DocumentBuilderFactory.newInstance();
docBuild = dbf.newDocumentBuilder();
doc = docBuild.parse(new File("test2.xml"));
System.out.println(doc.getFirstChild().getTextContent());
} catch(Exception e) {
e.printStackTrace();
}
}
}
但它返回我想要的文本(aaaaaaaaaaaaa")+其余元素的内部文本.输出:
But it returns the text I desire ("aaaaaaaaaaaaaa") + the inner text for the rest of the elements . Output:
Apples
Bananas
African Coffee Table
80
120
aaaaaaaaaaaaaa
要求不使用额外的 XML Java 库!
The requirement is not to use an additional XML java library !
推荐答案
@Kirill Polishchuk 的回答不正确:
建议:
a:root/text()
是一个相对表达式,如果它没有以根 (
/
) 节点作为上下文节点进行评估,则它不会在提供的 XML 文档中选择任何内容.
Is a relative expression and if it isn't evaluated having the root (
/
) node as the context node it selects nothing in the provided XML document.
即使是 XPath 表达式:/a:root/text()
也是不正确的,因为它选择了三个文本节点——所有文本节点的子节点顶部元素——包括两个纯空白文本节点.
Even the XPath expression: /a:root/text()
is incorrect, because it selects three text nodes -- all text node children of the top element -- including two whitespace-only text nodes.
这是一个正确的 XPath 解决方案:
/a:root/text()[string-length(normalize-space()) > 0]
当此 Xpath 表达式应用于提供的 XML 文档时(更正为格式正确):
<a:root
xmlns:a="UNDEFINED !!!!"
xmlns:h="http://www.w3.org/TR/html4/"
xmlns:f="http://www.w3schools.com/furniture">
<h:table>
<h:tr>
<h:td>Apples</h:td>
<h:td>Bananas</h:td>
</h:tr>
</h:table>
<f:table>
<f:name>African Coffee Table</f:name>
<f:width>80</f:width>
<f:length>120</f:length>
</f:table>
aaaaaaaaaaaaaa
</a:root>
它根据需要选择顶部元素的最后一个(并且只有非空白)文本节点子节点:
It selects the last (and only non-whitespace-only) text node child of the top element, as required:
aaaaaaaaaaaaaa
基于 XSLT 的验证:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:a="UNDEFINED !!!!"
>
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="/">
<xsl:text>"</xsl:text>
<xsl:copy-of select=
"/a:root/text()
[string-length(normalize-space()) > 0]"/>"
</xsl:template>
</xsl:stylesheet>
当对提供的 XML 文档(上图)应用此转换时,将输出所需的、正确选择的文本节点:
"
aaaaaaaaaaaaaa
"
这篇关于XML 文本提取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!