问题:在XML文件的节点属性中若有命名空间,怎样解析包含在命名空间内的属性? 
XML文件: 
<?xml version="1.0" encoding="UTF-8"?> 
<Medias> 
  <Media  xmlns="http://www.CIP4.org/JDFSchema_1_1" 
      MediaType="Paper" 
  </Media>    <Media  
      MediaType="Paper" 
  </Media>   <Media  MediaType="Paper" /> 
</Medias> java程序: 
import org.w3c.dom.*; 
import javax.xml.parsers.*; 
import java.io.*; 
import org.apache.xpath.XPathAPI; public class nodeSingle2 { public static void main(String[] args) { try{ 
String path="Medias.xml"; 
DocumentBuilderFactory domFactory=DocumentBuilderFactory.newInstance(); 
domFactory.setValidating(false); 
domFactory.setNamespaceAware(true); 
DocumentBuilder domBuilder=domFactory.newDocumentBuilder(); 
Document document=domBuilder.parse(new File(path));         String cond="//Media[@MediaType='Paper']";  //定义查找条件 
        NodeList lst=XPathAPI.selectNodeList(document,cond);//从document节点中进行查找符合条件的节点 
System.out.println(lst.getLength()); } 
    catch(Exception e){e.printStackTrace();} 
} } 输出结果: 
2 提问:怎样才能让输出结果为3 

解决方案 »

  1.   

      <Media  xmlns="http://www.CIP4.org/JDFSchema_1_1" 
          MediaType="Paper" 
      </Media>  这个定义的不太合理吧。外面在套个节点,加上命名空间,然后把《Media》都套进去不好点么
      

  2.   

    没太看懂啥意思
    http://cuishen.javaeye.com/blog/36054
      

  3.   

    http://cuishen.javaeye.com/blog/36054
    解决dom4j无法解析xml命名空间的问题去看看2楼给的网址
      

  4.   

    这样就可以了.public static void main(String[] args) throws UnsupportedEncodingException { try {
    String path = "Medias.xml";
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setValidating(false);
    domFactory.setNamespaceAware(false);
    DocumentBuilder domBuilder = domFactory.newDocumentBuilder();
    Document document = domBuilder.parse(new File(path)); String cond = "//Media[@MediaType='Paper']"; // 定义查找条件
    NodeList lst = XPathAPI.selectNodeList(document, cond);// 从document节点中进行查找符合条件的节点
    System.out.println(lst.getLength()); } catch (Exception e) {
    e.printStackTrace();
    } }
      

  5.   

    2楼的那个方法我看过了,不过那个是用的dom4j,和我用的接口不一致,不过也谢谢了非常感谢6楼,困扰了好几天的难题原来就改个布尔值这么简单,太谢谢了