0

I have a next XML file

<cities>
<country name="Абхазия">
    <city id="37188" region="27028" head="" type="3" country="Абхазия" part="" resort="" climate="">Новый Афон</city>
</country> 
</cities>

And i need to get the id attribute from the inner city node. I've done the next code, but i have no idea how to proceed:

        Document doc = parser.getDomElement(xml);
        NodeList nl = doc.getElementsByTagName(KEY_COUNTRY);

        for (int i = 0; i < nl.getLength(); i++) {

            Element e = (Element) nl.item(i);
            String city = parser.getValue(e, KEY_CITY);

        }
2

4 Answers 4

2

Use this methord.

NodeList nl = doc.getElementsByTagName("City");

        for (int i = 0; i < nl.getLength(); i++) {
            Node nNode = nl.item(i);
            if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                Element eElement = (Element) nNode;

                String id = eElement.getAttribute("id");

            }
        }
Sign up to request clarification or add additional context in comments.

1 Comment

Sure it will work.. First you have to get the elements by tag name country tag and get the attribute inside that tag. Inside the inner loop you have to get the elements by tag name city and get its attributes.
1
    NodeList nodeList = doc.getElementsByTagName("city");
    for (int i = 0; i < nodeList.getLength(); i++) {
        String id = nodeList.item(i).getAttributes().getNamedItem("id").getTextContent();
        //  do something with 'id'
        String cityName = nodeList.item(i).getTextContent();
        //  do something with 'cityName'
    }

5 Comments

Sorry, it won't work, i forgot that i have another tag. I edited my post.
@k.nadonenko I have checked - this code works with the last XML form. What are you trying to get in addition to the ID? From what attribute?
Sorry forgot to mention that i need not only the city id, also i need the city name.
<city id="37188" region="27028" head="" type="3" country="Абхазия" part="" resort="" climate="">Новый Афон</city> Here is the city name "Новый Афон".
@k.nadonenko Я думал, что тут подразумевался "Новый аЙфон". )
1
for(int i = 0; i < nl.getLength(); i++){ 
        Node n = nl.item(i);
        if (n.getNodeType() == Node.ELEMENT_NODE) {
            Element e = (Element)n;
            String yourId = e.getAttribute("KEY_CITY");
        }


}

Comments

0

Use XmlPullParser..... here is a link to a tutorial so u can get started with

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.