Reputation: 428
I am having an XML,which is like
<polygon>
<coordinates>
<coordinate order="1" long="75.9375" lat="32.91648534731439"/>
<coordinate order="2" long="76.640625" lat="23.241346102386135"/>
<coordinate order="3" long="88.59375" lat="31.052933985705163"/>
</coordinates>
</polygon>
I want to get the long and lat values of every coordinates and assign to string. I was trying like :
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse( new InputSource(new StringReader(s)));
System.out.println(document.getChildNodes());
NodeList nl = document.getElementsByTagName("coordinates");
for (int i = 0; i < nl.getLength(); i++)
{
System.out.println("name is : "+nl.item(i).getNodeName());
System.out.println("name is : "+nl.item(i).getNodeValue());
}
The String reader is the XML String I pass,but I am not able to get the data.
Upvotes: 0
Views: 89
Reputation: 27346
You need to cast each Node
into an Element
, and you need to make sure you're getting the right elements.
for(int i = 0; i < nl.getLength(); i++) {
Element e = (Element)nl.item(i);
String lat = e.getAttribute("lat");
String longStr = e.getAttribute("long");
}
Upvotes: 2
Reputation: 13726
Create the NodeList based on your hierarchy like below. Once you reach the childNode start iterating the nodelist casting with the Element and try to fetch the attribute value using the elementObject.getAttribute("tagname").
XML Structure:
polygon -> coordinates ->coordinate -> attributes - lat and long
NodeList valueList = doc.getElementsByTagName("polygon");
for (int i = 0; i < valueList.getLength(); ++i)
{
Element labTest = (Element) valueList .item(i);
String labTestType = labTest.getAttribute("type");
NodeList coordinates= labTest.getElementsByTagName("coordinates");
for (int j = 0; j < coordinates.getLength(); ++j)
{
Element value = (Element) coordinates.item(j);
String valueType = value.getAttribute("type");
NodeList coordinate= value.getElementsByTagName("coordinate");
for (int k = 0; k < coordinate.getLength(); ++k)
{
Element condition = (Element) coordinate.item(k);
String lat = e.getAttribute("lat");
String long = e.getAttribute("long");
}
}
}
Upvotes: 0