xml的DOM解析:
<?xml version="1.0" encoding="UTF-8"?> <books> <!--根节点--><!--这里的空白也算一个节点,所以books共有5个子节点--> <book id="book1" w="wwwww"> <name><a>AAAAAA</a>bookName1</name> <price>10.0</price> </book> <book id="book2"> <name>bookName2</name> <author>bookAuthor2</author> </book> </books>
这张图片才是精髓:
代码:
package com.zhang.xml.dom;
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 DomParse {
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse("books.xml"); //获得文档对象
Element element = document.getDocumentElement(); //获得根节点
NodeList books = element.getElementsByTagName("book"); //得到所有book节点,2个
// element.getChildNodes(); //得到所有子节点,5个
System.out.println("共有" + books.getLength() + "书");
for(int i=0; i<books.getLength(); i++) {
System.out.println("-----------------第" + (i+1) + "个节点开始解析-----------------");
Node bookNode = books.item(i); //得到第i个子节点
NamedNodeMap attrs = bookNode.getAttributes(); //得到节点的所有属性节点
System.out.println("---第"+ (i + 1) +"本书共有" + attrs.getLength() + "个属性节点---");
for(int j=0; j<attrs.getLength(); j++) {
Node attr = attrs.item(j); //得到第j个属性节点
String attrName = attr.getNodeName(); //节点名
String attrValue = attr.getNodeValue(); //节点值
System.out.println("------属性名:" + attrName + "-->属性值:" + attrValue + "------");
}
//如果知道book节点有且只有一个w属性节点
// Element ele = (Element)bookNode;
// System.out.println(ele.getAttribute("w"));
NodeList bookChildren = bookNode.getChildNodes(); //得到所有子节点
System.out.println("---第" + (i + 1) + "个节点共有" + bookChildren.getLength() +"个子节点---");
for(int k=0; k<bookChildren.getLength(); k++) {
if(bookChildren.item(k).getNodeType() ==Node.ELEMENT_NODE) {//元素节点
Node bookChild = bookChildren.item(k);
String nodeName = bookChild.getNodeName();
String textContent = bookChild.getTextContent();
// System.out.println(bookChild.getNodeValue()); //null
// System.out.println(bookChild.getFirstChild().getNodeValue()); // textContent
System.out.println("------第" + (k + 1) + "节点的节点名:" + nodeName + "-->节点值:" + textContent + "------");
}
}
System.out.println("-----------------第" + (i+1) + "节点结束解析-----------------");
System.out.println();
}
}
}
结果:
转载于:https://blog.51cto.com/yellowriver/1673436