org.w3c.dom.Document提供了getElementById的方法。可是我试了下,得到的Element为null
在网上看了下,说是设置SCHEMA,不太懂,请赐教。
xml文件如下所示<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<root>
<group id="1">
  <group id="2">
  </group>
</group>
</root>
如何找到id为2的element?

解决方案 »

  1.   


    <?xml   version= "1.0"   encoding= "UTF-8"   standalone= "no"?> 
    <root> 
    <group   id= "1 "> 
        <group   id= "2 ">7678
        </group> 
    </group> 
    </root> DocumentBuilderFactory domfac = DocumentBuilderFactory.newInstance();
    DocumentBuilder dombuilder = domfac.newDocumentBuilder();
    InputStream is = new FileInputStream("C:/xx.xml");
    Document doc = dombuilder.parse(is); NodeList nl = doc.getElementsByTagName("group");
    Element ele = null;
    for (int i = 0; i < nl.getLength(); i++) {
    Element e = (Element) nl.item(i); if (e.hasAttribute("id")) {
    if ("2 ".equals(e.getAttribute("id"))) {
    ele = e;
    System.out.println(e.getAttribute("id"));
    }
    }
    }
    if(ele != null) {
    System.out.println(ele.getTagName());
    System.out.println(ele.getTextContent());
    }
      

  2.   

    xpath.setNamespaceURIs(java.util.Collections.singletonMap("CNML",
    "http://www.cnml.org.cn/2005/CNMLSchema"));
      

  3.   

    <group   id= "1 "> id 为 1+空格  注意空格
      

  4.   


    貌似是的,注意你的xml格式
      

  5.   

    1楼方法很好,就是解析XML的DOM模式
      

  6.   

    demo4j 解析XML还是蛮强大的!
      

  7.   

    1楼方法很好,就是解析XML的DOM模式