Reputation: 21
I have program for reading XML file. Recently my supplier changed some part of the source XML file and I have no idea how to read the changed parts.
XML :
<Product>
<Weight>5,000</Weight>
<Color>blue</Color>
<Stock Warehouse_name="London" Availability="5,00"/>
<Stock Warehouse_name="Berlin" Availability="0,00"/>
<Stock Warehouse_name="Sydney" Availability="42,00"/>
</Product>
Maybe you see my problem already. Weight and Color are OK, but the Stock is my problem. Instead to give the information between the elements, the information is direct in the element. I'm using the standard method to retrieve the data:
color = (eElement.getElementsByTagName("Color").item(0).getTextContent());
Any suggestion? I'm pretty new to Java, so please explain it to me as simple, as possible.
Upvotes: 0
Views: 60
Reputation: 1171
You need to get the Stock nodes and convert to Element, then you can get the attribute you want.
final DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
// textoXml contains your xml file
final Document doc = dBuilder.parse(new ByteArrayInputStream(textoXml.getBytes()));
// Here you gat the Stock node you want and cast to Element
final Element eStock = (Element) doc.getElementsByTagName("Stock").item(0);
final String warehouseName = eStock.getAttribute("Warehouse_name");
You can see some other examples in https://www.mkyong.com/java/how-to-read-xml-file-in-java-dom-parser/
Upvotes: 2
Reputation: 14228
The values you want to retrieve are called attributes
.
You could use getAttribute
on Element
to retrieve the values of attributes.
Below code should work for the same :
NodeList stockList = eElement.getElementsByTagName("Stock");
for ( int i = 0; i < stockList.getLength(); i++ )
{
Node stockNode = stockList.item(i);
if ( stockNode.getNodeType() == Node.ELEMENT_NODE )
{
Element stockElement = (Element)stockNode;
System.out.println( "Warehouse name : " + stockElement.getAttribute( "Warehouse_name" ) );
System.out.println( "Availability : " + stockElement.getAttribute( "Availability" ) );
}
}
Upvotes: 0