标签:factory getattr static encoding rgs instance build version item
TestDom.java
package com.sxt.dom; import java.io.File; 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; /* * DOM解析文档:DOM把XML文档映射成一个倒挂的树,每个节点都是一个对象 * DOM:document object model 文档对象模型 * 缺点:1.前三步不能省略 * 2.空白节点没有过滤 */ public class TestDom { public static void main(String[] args) throws Exception { //创建解析工厂 DocumentBuilderFactory DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); //创建解析器 DocumentBuilder builder = factory.newDocumentBuilder(); //解析文档 获取文档内容 Document document = builder.parse(new File("product2.xml")); //拿到dom树 属性 元素 NodeList nodeList = document.getElementsByTagName("product"); //拿到根节点 Node node = nodeList.item(0);//Node getNodeType为1 System.out.println(node.getNodeName()); //拿到所有子节点 NodeList childNodes = node.getChildNodes(); //System.out.println(childNodes.getLength());//5 包括空白 空白也是子节点 //遍历子节点 包括空格 for(int i=0; i<childNodes.getLength(); i++){ Node childNode = childNodes.item(i); //System.out.println(childNode.getNodeType());//3表示空白 //如果节点不是空白 空白:TEXT_NODE if(childNode.getNodeType() == Node.ELEMENT_NODE){ String nodeName = childNode.getNodeName(); System.out.println(nodeName); //拿到属性的值 //Element是可以有属性和子节点的node。 getAttribute(String) Element childElem = (Element)childNode;//易错!!w3c下的Element String attribute = childElem.getAttribute("id"); System.out.println(attribute); //以根节点为例 继续找儿子节点 NodeList nodeList2 = childElem.getChildNodes(); for(int j=0; j<nodeList2.getLength(); j++){ Node node2 = nodeList2.item(j); if(node2.getNodeType() == Node.ELEMENT_NODE){ Element sonElem = (Element)node2; String name = sonElem.getNodeName(); String value = sonElem.getTextContent(); System.out.println(name +"\t"+ value); } } System.out.println(); } } } }
product2.xml (工程文件上右键 新建 other XML)
<?xml version="1.0" encoding="UTF-8"?> <!-- 外部DTD约束 --> <product> <item id = "P001"> <name>蜘蛛王皮鞋</name> <price>268</price> <color>黑色</color> <size>42</size> <stock>500</stock> </item> <item id = "P002"> <name>好皮鞋</name> <price>88</price> <color>蓝色</color> <size>42</size> <stock>100</stock> </item> </product>
标签:factory getattr static encoding rgs instance build version item
原文地址:http://www.cnblogs.com/qingfengzhuimeng/p/6803892.html