java 利用dom4j 读取 xml(xml文件的元素属性暂时不考虑) 把里面的元素以树的形式存储,然后中序遍历节点 20
<111><person><name>a</name><age>23</age><sex>f<sex></person><person><name>b</name><ag...
<111>
<person>
<name>a</name>
<age>23</age>
<sex>f<sex>
</person>
<person>
<name>b</name>
<age>21</age>
<sex>m<sex>
</person>
<person>
<name>c</name>
<age>29</age>
<sex>f<sex>
</person>
</111>
以树的形式存储节点 最后中序遍历 展开
<person>
<name>a</name>
<age>23</age>
<sex>f<sex>
</person>
<person>
<name>b</name>
<age>21</age>
<sex>m<sex>
</person>
<person>
<name>c</name>
<age>29</age>
<sex>f<sex>
</person>
</111>
以树的形式存储节点 最后中序遍历 展开
1个回答
展开全部
package xml;
import java.io.File;
import java.util.Iterator;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.DOMReader;
public class XmlTest {
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
File file = new File("d:/test.xml");
org.w3c.dom.Document domDocument = db.parse(file);
DOMReader reader = new DOMReader();
Document document = reader.read(domDocument);
Element root = document.getRootElement();
List skills = root.elements();
for (Iterator<?> it = skills.iterator(); it.hasNext();) {
Element e = (Element) it.next();
System.out.println(" "+e.getName());
List childrenList = e.elements();
for (Iterator<?> childit = childrenList.iterator(); childit.hasNext();){
Element e2 = (Element) childit.next();
System.out.println(" "+e2.getName()+"=="+e2.getText());
}
}
}
}
*****注意节点不能是纯数字.
import java.io.File;
import java.util.Iterator;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.DOMReader;
public class XmlTest {
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
File file = new File("d:/test.xml");
org.w3c.dom.Document domDocument = db.parse(file);
DOMReader reader = new DOMReader();
Document document = reader.read(domDocument);
Element root = document.getRootElement();
List skills = root.elements();
for (Iterator<?> it = skills.iterator(); it.hasNext();) {
Element e = (Element) it.next();
System.out.println(" "+e.getName());
List childrenList = e.elements();
for (Iterator<?> childit = childrenList.iterator(); childit.hasNext();){
Element e2 = (Element) childit.next();
System.out.println(" "+e2.getName()+"=="+e2.getText());
}
}
}
}
*****注意节点不能是纯数字.
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询