我需要幫助使xpath表達式讀取xml字符串中的所有節點名稱,節點值和屬性。我做了這個:Java,用於讀取所有節點名稱,節點值和屬性的XPath表達式
private List<String> listOne = new ArrayList<String>();
private List<String> listTwo = new ArrayList<String>();
public void read(String xml) {
try {
// Turn String into a Document
Document document = DocumentBuilderFactory.newInstance()
.newDocumentBuilder().parse(new ByteArrayInputStream(xml.getBytes()));
// Setup XPath to retrieve all tags and values
XPath xPath = XPathFactory.newInstance().newXPath();
NodeList nodeList = (NodeList) xPath.evaluate("//text()[normalize-space()='']", document, XPathConstants.NODESET);
// Iterate through nodes
for(int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
listOne.add(node.getNodeName());
listTwo.add(node.getNodeValue());
// Another list to hold attributes
}
} catch(Exception e) {
LogHandle.info(e.getMessage());
}
}
我在網上找到了表達式//text()[normalize-space()='']
;但是,它不起作用。當我嘗試從listOne
獲取節點名稱時,它只是#text
。我試過//
,但那也行不通。如果我有這個XML:
<Data xmlns="Somenamespace.nsc">
<Test>blah</Test>
<Foo>bar</Foo>
<Date id="2">12242016</Date>
<Phone>
<Home>5555555555</Home>
<Mobile>5555556789</Mobile>
</Phone>
</Data>
listOne[0]
應持有Data
,listOne[1]
應持有Test
,listTwo[1]
應持有blah
,等等......所有屬性將被保存在另一個平行的列表中。
xPath
應該評估什麼樣的表達?
注:XML字符串可以有不同的標籤,所以我不能硬編碼任何東西。
更新:嘗試這個循環:
NodeList nodeList = (NodeList) xPath.evaluate("//*", document, XPathConstants.NODESET);
// Iterate through nodes
for(int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
listOne.add(i, node.getNodeName());
// If null then must be text node
if(node.getChildNodes() == null)
listTwo.add(i, node.getTextContent());
}
但是,這僅獲得根元素Data
,然後就停止。
'text()'指元素內容。在您的示例XML中,'blah','bar'和'12242016'是文本節點。所以,'text()'可能不是你想要的。 – VGR
謝謝!如果'text()'給出元素的內容,那麼'node()'會給節點? – syy
我認爲可能需要一些澄清。在XML中,「節點」是指XML文檔中的每一個可能的信息,包括文本,註釋,處理指令等,而「元素」是指由開始標記和匹配結束標記組成的信息,或者單個自動關閉標籤(' ')。你真的想讀每個節點,或只是每個元素及其屬性? –
VGR