确定节点是否是CDATA部分



我正在尝试从XML节点中获得值,并在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)...

问题只有在包含诸如" test"one_answers" textContent"之类的数据时,我才能获得节点的值,但对于" root"之类的节点?

谢谢。

我提出了这个解决方案...不确定这是否是正确的方法,但似乎可以按预期工作。

因此,要获取节点的值,例如" test"或" helpcontent",我使用以下内容更新了代码:

NodeList childs = node.getChildNodes();
if (childs.getLength() == 1){
    System.out.println("TextContent: " + node.getTextContent());
}

最新更新