XML解析。试图获得属性

时间:2013-04-09 08:27:27

标签: java xml

我正在开发一个java类来解析这个xml文件:

<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>

我有这个java类:

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();
}

正如您所看到的,它为每个“模块”标记循环并获取其子值。但是我需要来自模块的name属性,但是因为它是NodeList,所以不能使用方法getAttribute("name");

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

你可以做到

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

检索代表name标记的节点的module atttribute。您可以这样做,因为module标签本身也是一个元素。 getAttribute()方法记录在案here

答案 1 :(得分:1)

doc.getElementsByTagName("module")

返回具有给定标记名称的元素列表,即模块,当您迭代节点列表时,必须在for语句中使用 getAttribute 函数。

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