xml例程不处理我想要的子节点

时间:2014-04-04 06:21:19

标签: java xml dom

    <report id="oleg">
        <title>olegitimerade rapport</title>
        <id_email>joch1</id_email>
        <id_email>kang15</id_email>
    </report>

我使用以下代码与DOM XML解析器一起提取上面的列表xml文件。

String tag = "report";
String[] elementTags = new String[] {"title", "id_email"};

NodeList nList = this.doc.getElementsByTagName(tag);

    try{
        for (int temp = 0; temp < nList.getLength(); temp++) {

            Node nNode = nList.item(temp);

            if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                HashMap<String, String> attribute = new HashMap<String, String>();
                Element eElement = (Element) nNode;

                if(eElement.hasAttribute("id")){
                    String id = eElement.getAttribute("id");

                    attribute.put("id", id);            

                    for (String elementTag : elementTags){
                        try{

                            int index=0;

                            while(null!=eElement.getElementsByTagName(elementTag).item(index).getTextContent()){
                                attribute.put(elementTag, eElement.getElementsByTagName(elementTag).item(index).getTextContent());
                                index++;
                            }
                        }catch (Exception e){
                            //System.out.println("id : "+id+" - Attribute element '"+ elementTag+ "' not found in XML! ["+this.xmlFile+"]");
                        }   
                    }

                    attributes.add(attribute);
                }
            }
        }
    }catch (Exception e) {
        e.printStackTrace();
    }

问题是我得到多个标签....我无法提取第二个ID(kang15)。

很明显,while循环是不正确的,所以我需要一些帮助解决这个问题。

   while(null!=eElement.getElementsByTagName(elementTag).item(index).getTextContent()){
                            attribute.put(elementTag, eElement.getElementsByTagName(elementTag).item(index).getTextContent());
                            index++;
                        }

1 个答案:

答案 0 :(得分:0)

考虑使用XPath

XPath xpath = XPathFactory
    .newInstance()
    .newXPath();
Element report = (Element) xpath.evaluate("//report", doc, XPathConstants.NODE);
String id = xpath.evaluate("@id", report);
String title = xpath.evaluate("title", report);
NodeList emails = (NodeList)
              xpath.evaluate("id_email/text()", report, XPathConstants.NODESET);

System.out.println(id);
System.out.println(title);
for(int i=0; i<emails.getLength(); i++) {
  System.out.println(emails.item(i).getTextContent());
}