![](/img/trans.png)
[英]Unable to get root node value from True. Instead gives the last nodes' value
[英]Get the value of nodes inside a node
我一直在努力為我的問題找到一個明確的解決方案,因為到目前為止我發現的每一個解釋都令人困惑(至少對我而言)。
我試過 DOM 閱讀器,但我不能用這個文件來補充它,因為它是一個更復雜的 XML 文件。
我的 XML 文件:
<Order>
<OrderID>
<OrderConfirmationDate>
<Date>
<Year>2000</Year>
<Month>10</Month>
<Day>06</Day>
</Date>
</OrderConfirmationDate>
<Adress>
<Name>Papel do Porto</Name>
<Address1>Rua da Alegria</Address1>
<Address2>nº1</Address2>
<City>Porto</City>
<PostalCode>4000-032</PostalCode>
<Country ISOCountryCode="PT">Portugal</Country>
</NameAddress>
這是我到目前為止所理解的代碼
dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(xmlFile);
doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
因此,我可以使用getDocumentElement()
輕松獲取文檔的根目錄。 我可以使用getNodeName()
輕松獲取根節點。
但是我如何獲得"node.getNodeName().
(在這種情況下,我的意思是從<OrderID>
中獲取<OrderConfirmationDate>
)另外,我讀過像<Year>
和<Month>
這樣的標簽是節點<Date>
。
要 select 特定節點,可以使用XPath表達式。
XPath xpath = XPathFactory.newDefaultInstance().newXPath();
XPathExpression expr = xpath.compile("//OrderConfirmationDate/Date");
Element orderConfirmationDateElement = (Element) expr.evaluate(doc, XPathConstants.NODE);
然后通過節點的子節點到 go:
NodeList dateChildren = orderConfirmationDateElement.getChildNodes();
for(int i = 0; i < dateChildren.getLength(); i++) {
if (dateChildren.item(i).getNodeType() == Node.ELEMENT_NODE) {
System.out.println(dateChildren.item(i).getNodeName() + ": " + dateChildren.item(i).getTextContent());
}
}
Output:
Year: 2000
Month: 10
Day: 06
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.