1

I'm developing a java class to parse this xml file:

<document src="xmls/sections/modules/200_1.xml">
<module name="product_info" id="1">
    <product_primary_id>200</product_primary_id>
    <product_section_id>1</product_section_id>
    <product_section_item_id></product_section_item_id>

    <type>1</type>
    <position>1</position>
    <align>top</align>

    <url href="productview/info.html"></url>
</module>
</document>

And I've this java class:

try {
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(contingut);
    doc.getDocumentElement().normalize();
    //loop a cada module
    NodeList nodes = doc.getElementsByTagName("module");
    for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        Element element = (Element) node;
        if(element.getNodeType() == Element.ELEMENT_NODE){
            Log.d("debugging","product_primary_id: "+getValue("product_primary_id",element));
            Log.d("debugging","product_section_id: "+getValue("product_section_id",element));
            //Log.d("debugging","product_section_item_id: "+getValue("product_section_item_id",element));
            Log.d("debugging","type: "+getValue("type",element));
            Log.d("debugging","position: "+getValue("position",element));
            Log.d("debugging","align: "+getValue("align",element));
            //Log.d("debugging","url: "+getValue("url",element));   
        }
    }
} catch (Exception e){
            e.printStackTrace();
}

As you can see, it's looping for every "module" tag and getting its child value. But I need name attribute from module, but as It's a NodeList, can't use method getAttribute("name");

Any idea?

2 Answers 2

2

You can just do

Element element = (Element) node;
element.getAttribute("name")

to retrieve the name atttribute for the node that represents the module tag. You can do so because the module tag is an element itself, too. The getAttribute() method is documented here.

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

Comments

1
doc.getElementsByTagName("module")

Returns a List of elements with the given tag name i.e. module, you have to use the getAttribute function inside of your for statement, when you are iterating over the list of nodes.

See http://docs.oracle.com/javase/7/docs/api/org/w3c/dom/Document.html#getElementsByTagName%28java.lang.String%29

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.