日期:2014-05-20 浏览次数:20800 次
<?xml version="1.0" encoding="GB2312" standalone="no"?>
<公司人员 xmlns:p1="first://www.dlrin.com" xmlns:p2="second://www.dlrin.com">
<p1:张三>1989年出生,毕业于上海交通大学</p1:张三>
<p2:张三>1972年出生,毕业于中国科学技术大学</p2:张三>
<李四>1985年出生,毕业于北京大学</李四>
</公司人员>
public class test {
public static void main(String[] args) throws Exception{
DocumentBuilderFactory docbudfact = DocumentBuilderFactory.newInstance() ;
DocumentBuilder docbud = docbudfact.newDocumentBuilder() ;
Document doc = docbud.parse(new File("a.xml"));
Element element = doc.getDocumentElement();
NodeList nodelist = element.getElementsByTagNameNS("second://www.dlrin.com", "张三");
findNodeMessage(nodelist);
nodelist = element.getElementsByTagName("李四");
findNodeMessage(nodelist);
}
public static void findNodeMessage(NodeList nodelist) {
int size = nodelist.getLength() ;
for(int k=0 ; k<size ; k++ ){
Node node = nodelist.item(k) ;
String name = node.getNodeName() ;
int index = name.indexOf(":");
if(index != -1){
name = name.substring(index+1) ;
}
String content = node.getTextContent() ;
content = content.trim() ;
System.out.println(name+":"+content);
}
}
}
DocumentBuilderFactory docbudfact = DocumentBuilderFactory
.newInstance();
try {
DocumentBuilder docbud = docbudfact.newDocumentBuilder();
Document doc = docbud.parse(new File("a.xml"));
Element element = doc.getDocumentElement();
NodeList nodelist = element.getElementsByTagNameNS(
"second://www.dlrin.com", "p1:张三");
//"second://www.dlrin.com", "p2:张三");
nodelist = element.getElementsByTagName("张三");
findNodeMessage(nodelist);
nodelist = element.getElementsByTagName("李四");
findNodeMessage(nodelist);
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//我测试了 可以得到张三
//1989年出生,毕业于上海交通大学
NodeList nodelist = element.getElementsByTagNameNS( "second://www.dlrin.com", "p1:张三");
//张三>1972年出生,毕业于中国科学技术大学
NodeList nodelist = element.getElementsByTagNameNS( "second://www.dlrin.com", "p2:张三");