设想:
给定以下 XML 文件:
<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>
如何提取主元素内的文本<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();
}
}
}
但它返回我想要的文本(“aaaaaaaaaaaaaa”)+其余元素的内部文本。输出:
Apples
Bananas
African Coffee Table
80
120
aaaaaaaaaaaaaa
要求是not使用额外的 XML java 库!
@Kirill Polishchuk 的答案不正确:
提议:
a:root/text()
是一个相对表达如果没有评估其根(/
) 节点作为上下文节点,它在提供的 XML 文档中不选择任何内容。
甚至 XPath 表达式:/a:root/text()
是不正确的,因为它选择三个文本节点(顶部元素的所有文本节点子节点),其中包括两个仅包含空格的文本节点。
这是正确的 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>
它根据需要选择顶部元素的最后一个(也是唯一非空白)文本节点子节点:
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
"
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)