简体   繁体   中英

XML Parsing. Trying to get attributes

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?

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 .

doc.getElementsByTagName("module")

Returns a List of elements with the given tag name ie 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM