当xml中有两个相似的标记时,XML的getNodeValue

时间:2011-07-14 06:08:06

标签: java dom xml-parsing

我正在使用DOM来解析xml,但遇到了一个问题。在我的xml中,我有三个标签,即 str int str 。现在,在解析时,我得到 str 标签的相同值,而它们应该是不同的。

我的XML

<result name="response" numFound="62996" start="0">
    <doc>
        <str name="body">
            a b c d e f g h i j k l m n o p q r s t u v w x  y z
        </str>
        <int name="content_id">123351</int>
        <str name="title">
            Alphabets
        </str>
    </doc>
</result>

xml解析代码

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        InputSource is = new InputSource();
        is.setCharacterStream(new StringReader(gXml));
        Document doc = db.parse(is);
        NodeList infraline1 = doc.getElementsByTagName(node);

        sb.append("<results count=");
        sb.append("\"10\"");
        sb.append(">\r\n");

        for (int i = 0; i < infraline1.getLength(); i++) {
            Node node1 = infraline1.item(i);
            if (node1.getNodeType() == Node.ELEMENT_NODE) {
                Element element = (Element) node1;
                NodeList nodelist = element.getElementsByTagName("str");
                Element element1 = (Element) nodelist.item(0);
                NodeList body = element1.getChildNodes();
                sb.append("<result>\r\n");
                sb.append("<body>");
                    sb.append((body.item(0)).getNodeValue().trim());
                sb.append("</body>\r\n");
                if (node1.getNodeType() == Node.ELEMENT_NODE) {
                    Element element2 = (Element) node1;
                    NodeList nodelist1 = element2.getElementsByTagName("int");
                    Element element3 = (Element) nodelist1.item(0);
                    NodeList id = element3.getChildNodes();
                    sb.append("<id>");
                        sb.append(id.item(0).getNodeValue().trim());
                    sb.append("</id>\r\n");
                }
                if(node1.getNodeType() == Node.ELEMENT_NODE){
                    Element element4 = (Element) node1;
                    NodeList nodelist2 = element4.getElementsByTagName("str");
                    Element element5 = (Element) nodelist2.item(0);
                    NodeList title = element5.getChildNodes();
                    sb.append("<title>");
                        sb.append(title.item(0)).getNodeValue());
                    sb.append("</title>\r\n");
                }
                sb.append("</result>\r\n"); 
            }
        }
        sb.append("</results>");
    }

请帮忙,因为我需要为 str 节点

获取不同的值

1 个答案:

答案 0 :(得分:0)

我只看到陈述

Element element1 = (Element) nodelist.item(0);

Element element3 = (Element) nodelist.item(0);

您确定,您正在访问正确的元素。

......顺便说一句。代码真的很混乱,因为您一次解析和写入数据。尝试将解析后的XML放入自己的ObjectMap中,然后再写入(格式化)