XML内容(放入项目中)
class="java" name="code">
<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
<book id="1">
<name>冰与火之歌</name>
<author>乔治马丁</author>
<year>2014</year>
<price>89</price>
</book>
<book id="2">
<name>安徒生童话</name>
<year>2004</year>
<price>77</price>
<language>English</language>
</book>
</bookstore>
代码实现
import java.awt.print.Book;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class XmlDOM {
public static void main(String[] args) {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = dbf.newDocumentBuilder();
Document document = builder.parse("xml/001.xml");
//nodeList获取所有节点的集合
NodeList nodeList = document.getElementsByTagName("book");
//便利每一个book节点
for(int i=0;i<nodeList.getLength();i++){
System.out.println("------------------------------------------j第" + (i+1) + "本书信息");
//获取book节点
Node book = nodeList.item(i);
/* //获取到书的所有信息
NamedNodeMap bookMap = book.getAttributes();
//遍历
for(int n=0;n<bookMap.getLength();n++){
Node attr = bookMap.item(n);
//获取属性名/获取属性值
System.out.println("属性名:"+attr.getNodeName() + "" + "属性值:" + attr.getNodeValue());
}*/
NodeList childNodes = book.getChildNodes();
for(int j=0;j<childNodes.getLength();j++){
//区分出text类型的node以及element类型的node
if(childNodes.item(j).getNodeType() == Node.ELEMENT_NODE){
//获取了Element节点的节点名
System.out.println(childNodes.item(j).getNodeName() + "=" + childNodes.item(j).getTextContent());
}
}
}
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
执行结果:
------------------------------------------j第1本书信息
name=冰与火之歌
author=乔治马丁
year=2014
price=89
------------------------------------------j第2本书信息
name=安徒生童话
year=2004
price=77
language=English