问题:在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
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
MediaType="Paper"
</Media> 这个定义的不太合理吧。外面在套个节点,加上命名空间,然后把《Media》都套进去不好点么
http://cuishen.javaeye.com/blog/36054
解决dom4j无法解析xml命名空间的问题去看看2楼给的网址
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();
} }