I have an xml like this :
<cargalery>
<garage garagetype="Expensive" garagename="Garage1">
<cars cartype="faster" carname="Car4" />
<cars cartype="faster" carname="Car5" />
<cars cartype="slower" carname="Car6" />
</garage>
<garage garagetype = "Cheap" garagename="Garage2">
<cars cartype="slower" carname="Car1" />
<cars cartype="faster" carname="Car2" />
<cars cartype="slower" carname="Car3" />
</garage>
</cargalery>
I can read garage nodes with that :
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
URL u = new URL("xmlurl");
Document doc = builder.parse(u.openStream());
doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
NodeList NodeOzet = doc.getElementsByTagName("garage");
for (int temp = 0; temp < NodeOzet.getLength(); temp++)
{
Node nOzet = NodeOzet.item(temp);
System.out.println("\nCurrent Element :" + nOzet.getNodeName());
if (nOzet.getNodeType() == Node.ELEMENT_NODE)
{
Element eElement = (Element) nOzet;
System.out.println("Garage Name : " + eElement.getAttribute("garagename"));
}
}
But I can not read garage inside cars. How can I read cars inside garage ?
Thanks.
For an Element
is defined the method getAttribute("AttributeName")
.
If you want the name of the cars inside a garage you are doing right by creating a NodeList
within all the elements by tag name "garage", then you should create a nested for loop, to get all the elements by tag name "cars" inside your garage.
for (int temp = 0; temp < NodeOzet.getLength(); temp++){
Node nOzet = NodeOzet.item(temp);
NodeList carList = eElement.getElementsByTagName("cars")
String cars = "";
for(int temp2 = 0; temp2 < carList.getLength(); temp2++){
cars += ((Element)carList.item(temp2)).getAttribute("carname") + "\t";
}
}
Like this for each garage you get all the cars inside the garage, and their names
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments