Java原生实现DOM树解析XML文件
一、测试用的XML文件
<?xml version="1.0" encoding="UTF-8" ?>
<bookstore>
<book id="1">
<name>书1</name>
<author>作者1</author>
<price>¥998</price>
</book>
<book id="2">
<name>书2</name>
<author>作者2</author>
<price>¥998</price>
</book>
<book id="3">
<name>书3</name>
<author>作者3</author>
<price>¥998</price>
</book>
</bookstore>
二、解析XML文件
public class DomDemo {
public static void main(String[] args) {
InputStream inputStream = DomDemo.class.getClassLoader().getResourceAsStream("test.xml");
DocumentBuilderFactory dom = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder domBuilder = dom.newDocumentBuilder();
Document document = domBuilder.parse(inputStream);
Element bookstore = document.getDocumentElement();
System.out.println(bookstore.getTagName());
NodeList bookList = bookstore.getElementsByTagName("book");
for (int i = 0; i < bookList.getLength() ; i++) {
Node book = bookList.item(i);
NamedNodeMap bookAttributes = book.getAttributes();
for (int j = 0; j < bookAttributes.getLength(); j++) {
Node node = bookAttributes.item(j);
if (node.getNodeType() == Node.ATTRIBUTE_NODE){
System.out.println(node.getNodeName()+":"+node.getNodeValue());
}
}
NodeList bookChildList = book.getChildNodes();
for (int j = 0; j < bookChildList.getLength(); j++) {
Node childItem = bookChildList.item(j);
if (childItem.getNodeType() == Node.ELEMENT_NODE){
System.out.println(childItem.getNodeName()+":"+childItem.getTextContent());
}
}
System.out.println("=======================");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
三、稍微有点麻烦了,建议使用Jsoup,操作更加方便
bookstore
id:1
name:书1
author:作者1
price:¥998
=======================
id:2
name:书2
author:作者2
price:¥998
=======================
id:3
name:书3
author:作者3
price:¥998
=======================
原文作者:絷缘
作者邮箱:zhiyuanworkemail@163.com
原文地址:https://zhiyuandnc.github.io/fIrwGdZp7/
版权声明:本文为博主原创文章,转载请注明原文链接作者信息