0
說我有一個xml文檔並希望從每個bitl =中獲取所有文本節點。從XML中提取單個節點中的所有文本字段
<Stuff>
<data>
<Nodes>
<NodeID>1</NodeID>
<Name>thingA</Name>
<MoreInfo>
<Description>Scooter</Description>
</MoreInfo>
</Nodes>
<Nodes>
<NodeID>2</NodeID>
<Name>thingB</Name>
<MoreInfo>
<Description>Bike</Description>
</MoreInfo>
</Nodes>
</data>
</Stuff>
我想提取每個文本。
所以我最終得出:1,thingA,Scooter;和2,thingB,Bike。
NodeList nodes = (NodeList) xpath.evaluate("Nodes", resultXml, XPathConstants.NODESET);
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
logger.info("Evaluating: " + node.toString());
// How do I get just the text nodes descending from the "node" I just found,
// without knowing what the actual node names? I wan't this to work
// for any list of nodes, no matter what the sub-element names are.
}
我做了「NodeList fieldNodes =(NodeList)xpath.evaluate(」// text()[normalize-space()]「,node);」並打印出我找到的每個節點的內容。在評估節點時,它會打印出文件中其他位置隨機字段的多個副本。 – exxodus7
評價: thingA 踏板車描述> 找到12字段的節點。 thingyB thingyB thingyB thingyB thingyB ... –
exxodus7
不,我的建議是使用'節點列表節點=(節點列表)xpath.evaluate( 「//文本()[正常化空間()]」,resultXml, XPathConstants.NODESET);'而不是'NodeList節點=(NodeList)xpath.evaluate(「節點」,resultXml,XPathConstants.NODESET);'。或者'NodeList nodes =(NodeList)xpath.evaluate(「//節點// text()[normalize-space()]」,resultXml,XPathConstants.NODESET);'。然後您不需要進一步評估,您可以簡單地訪問所選節點列表/節點集中的節點。 –