Reputation: 91
I've been trying to find a clear solution for my problem since every explanation I've found until now its confusing (for me at least).
I've tried DOM readers but I can't complement it with this file since its a more complex XML file.
My XML file:
<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>
This is the code I've understood until now
dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(xmlFile);
doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
So, I can easily get the root of document with getDocumentElement()
. And I can easily get a node of the root with getNodeName()
.
But how do I get the "node.getNodeName().
(in this case I mean to get the <OrderConfirmationDate>
out of <OrderID>
)
Also, I've read that tags like <Year>
and <Month>
are Ids of the node <Date>
.
Upvotes: 0
Views: 240
Reputation: 148
To select a particular node, you can use a XPath expression.
XPath xpath = XPathFactory.newDefaultInstance().newXPath();
XPathExpression expr = xpath.compile("//OrderConfirmationDate/Date");
Element orderConfirmationDateElement = (Element) expr.evaluate(doc, XPathConstants.NODE);
Then to go through the node's children:
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
Upvotes: 1