我在解析Java中的XML文件時遇到了一些麻煩。該文件的形式爲:帶有重複標籤的XPath和Java
<root>
<thing>
<name>Thing1</name>
<property>
<name>Property1</name>
</property>
...
</thing>
...
</root>
最後,我想這個文件轉換成的事對象的列表,這將有一個String名稱(Thing1)和Property對象的名單,這將各自也有一個名字(Property1)。
我一直在試圖使用xpaths來獲取這些數據,但是當我試圖得到'thing'的名字時,它給了我所有出現在'thing'中的名字,包括那些「酒店的。我的代碼是:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document dom = db.parse(filename);
XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression thingExpr = xpath.compile("//thing");
NodeList things = (NodeList)thingExpr.evaluate(dom, XPathConstants.NODESET);
for(int count = 0; count < things.getLength(); count++)
{
Element thing = (Element)things.item(count);
XPathExpression nameExpr = xpath.compile(".//name/text()");
NodeList name = (NodeList) nameExpr.evaluate(thing, XPathConstants.NODESET);
for(int i = 0; i < name.getLength(); i++)
{
System.out.println(name.item(i).getNodeValue());
}
}
任何人都可以幫忙嗎?提前致謝!
輸出,它似乎並不認爲你已經表示要生產使用什麼XPath - 即使考慮了評論。 Xpath用於選擇我們感興趣的某些特定節點 - 它們是在您的特定情況下?你想從這些特定節點提取哪些數據?請編輯問題並指定這些缺失和重要的信息。 –