确定节点是否是CDATA节
问题描述:
我试图从XML节点中获取值并在CDATA节中运行问题。确定节点是否是CDATA节
我的XML的样子:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<root>
<Test>This is my node</Test>
<HelpContent><![CDATA[this is the CDATA section]]></HelpContent>
</root>
与此代码:
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(currentFile);
XPathFactory xPathFactory = XPathFactory.newInstance();
XPath xpathObj = xPathFactory.newXPath();
XPathExpression expr = xpathObj.compile("//*");
NodeList nodes = (NodeList)expr.evaluate(doc, XPathConstants.NODESET);
int len = nodes.getLength();
for (int i = 0; i < len; i++){
Node node = nodes.item(i);
System.out.println("Node name [" + node.getNodeName() + "] of type [" + node.getNodeType() + "]");
System.out.println("NodeValue: " + node.getNodeValue());
System.out.println("TextContent: " + node.getTextContent());
}
我有以下几点:
> Node name [root] of type [1]
> NodeValue: null
> TextContent: This is my
> node this is the CDATA section
>
> Node name [Test] of type [1]
> NodeValue: null
> TextContent: This is my node
>
> Node name [HelpContent] of type [1]
> NodeValue: null
> TextContent: this is the CDATA section
正如你所看到的,节点具有子(在这种情况下只有根)我得到了所有从儿童节点中提取的文本。 另外,你可以看到getNodeType总是重新调整1(ELEMENT_NODE)...
问我怎么能拿节点的值只有在包含了诸如“测试”和“的TextContent”,但数据为空或null像节点“根”?
谢谢。
答
我拿出这个解决方案...不知道这是否是正确的方法来做到这一点,但似乎按预期工作。
因此,要像“测试”或节点值“HelpContent”我更新了下面的代码:
NodeList childs = node.getChildNodes();
if (childs.getLength() == 1){
System.out.println("TextContent: " + node.getTextContent());
}
的可能的复制[如何检索通过XPath的CDATA标记内的元素文本? ](https://stackoverflow.com/questions/568315/how-do-i-retrieve-element-text-inside-cdata-markup-via-xpath) –
链接的副本解释了XPath忽略CDATA节点。如果你走DOM而不是使用XPath,你应该能够找到它们。 –
在DOM中,Node.getNodeValue()对于一个元素节点为空。 https://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-F68D080。您可能想向我们展示一个最小但完整的样本,以便我们重现您所说的结果,并解释您期望的结果。 –