如何解析android中的xml标签组?

时间:2011-11-10 13:18:04

标签: android xml-parsing

民间,

这是我的xml回复:

<parent>
<child>
<name>
<age>
</child>
<child>
<name>
<age>
</child>
...</parent>

我需要将每个子内容解析为xml字符串:

需要输出:

<child>
<name>
<age>
</child>

我也使用了normalize方法。但我仍然面临着获得正确输出的问题。

我的代码是:

NodeList nodes = document.getElementsByTagName("child");// here documentobject is the Document of my xml.

for (int i = 0; i < nodes.getLength(); i++) {
    Node element = nodes.item(i);
    // nodes.item(i).normalize();    
    System.out.println(nodes.item(i).getNodeValue());
}

任何想法?

2 个答案:

答案 0 :(得分:1)

为此,您要使用getTextContent()而非getNodeValue() ....

NodeList nodes = doc.getElementsByTagName("child");
        for (int i = 0; i < nodes.getLength(); i++) {           
            if (nodes.item(i).getNodeType() == Node.ELEMENT_NODE) {
                NodeList msgChildren = nodes.item(i).getChildNodes();
                for (int j = 0; j < msgChildren.getLength(); j++) {
                    if (msgChildren.item(j).getNodeType() == Node.ELEMENT_NODE) {
                        Element e = (Element) msgChildren.item(j);
                        System.out.println("<"+e.getNodeName()+">");
                        System.out.println(e.getTextContent());
                        System.out.println("</"+e.getNodeName()+">");                        
                    }
                }
            }
        }

答案 1 :(得分:0)

检查以下代码段:

        NodeList items_records = element.getElementsByTagName("child");
            for (int a = 0; a < items_records.getLength(); a++) {
                Node item_records = items_records.item(a);
                NodeList properties_records = item_records.getChildNodes();
                for (int b = 0; b < properties_records.getLength(); b++) {
                    Node property_records = properties_records.item(b);
                    String name_records = property_records.getNodeName();

                    try{
                        if (name_records.equalsIgnoreCase("name")) {
                           parsed_total_records_value = property_records.getFirstChild().getNodeValue(); 
                           Log.v("parsed_total_records_value",parsed_total_records_value);
                        }
                    }catch(Exception e){
                }   
            }
        }