用getElementsByTagName取xml子节点问题
<?xml version= "1.0 " encoding= "UTF-8 "?>
<test>
<object name= "n1 " level= "1 ">
<object name= "2 " level= "2 "> </object>
</object>
<object name= "n3 " level= "1 ">
<object name= "4 " level= "2 "> </object>
</object>
</test>
============
以上是XML文件内容(文件格式是utf-8),注意object节点分成二个层次,object中包含了另一个object.
我现在想把object逐层取出来,但发现用getElementsByTagNam( "object ")会一次性把所有的 <object> 节点取出. 说以下代码,总是返回所有的object节点, 我实际上想先取出第一层object,然后再取根据第一层往下找.
import org.w3c.dom.*
...
Document doc = ...
Element root = doc.getDocumentElement();
NodeList students = root.getElementsByTagName( "object ");
for (int i = 0; i < students.getLength(); i++) {
}
------解决方案--------------------Element root=doc.getRootElement()//得到根元素
java.util.List students=root.getChildren()//得到根元素所有的子元素的集合
java.util.List a=student.getChildren()//得到a元素所有的子元素的集合
------解决方案--------------------import org.w3c.dom.*
...
Document doc = ...
Element root = doc.getDocumentElement();
NodeList students = root.getChildNodes();
for (int i = 0; i < students.getLength(); i++) {
System.out.println(students.item(i).getAttributes());//有空格,是文件内容缩进,可以判断剔除.
}
------解决方案--------------------Element继承自Node接口,里面有很多方法可以用
import org.w3c.dom.*
...
Document doc = ...
Element root = doc.getDocumentElement();
Node child = root.getFirstChild();
while(child.getNextSibling()!=null)
{
......
child = child.getNextSibling()
}
------解决方案--------------------关键用XPathAPI.selectNodeList(doc, "节点/子节点/... ")
注意:org.apache.xpath.XPathAPI 类已经移植到了 JRE 1.5 中,重构为com.sun.org.apache.xpath.internal.XPathAPI
以下为jsp代码例子
<%@ page language= "java " contentType= "text/html; charset=UTF-8 "pageEncoding= "UTF-8 "%>
<%@ page import= "javax.xml.parsers.* "%>
<%@ page import= "javax.xml.parsers.DocumentBuilderFactory "%>
<%@ page import= "org.apache.xpath.* "%>
<%@ page import= "java.io.File "%>
<%@ page import= "org.w3c.dom.* "%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN " "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<html xmlns= "http://www.w3.org/1999/xhtml ">
<head>
</head>
<body>
<%
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new File( "D:\\Java\\Work\\space\\WebContent\\test\\x.xml "));
NodeList accountNodes = XPathAPI.selectNodeList(doc, "/a/aaa ");
for (int accountNodeIndex = 0; accountNodeIndex < accountNodes.getLength(); accountNodeIndex++) {