IT程序员开发必备-各类资源下载清单,史上最全IT资源,个人收藏总结!
package edu.jvm;import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import com.sun.xml.internal.bind.v2.schemagen.xmlschema.List;
public class Jaxp_dom {
//得到代表文档的document对象
@Test
public void analyDocument() throws SAXException, IOException, ParserConfigurationException{
//1.创建工厂
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
//2.得到dom解析器
DocumentBuilder builder = factory.newDocumentBuilder();
//3.解析xml文档,得到代表文档的document
Document document = builder.parse("WebRoot/product.xml");
}
//递归打印所有的标签(Element)名称
@Test
public void printTagName() throws SAXException, IOException, ParserConfigurationException{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse("WebRoot/product.xml");
//得到根节点:
Node root = document.getElementById("cata1");
//递归调用输出节点名称及其子节点
printChildrenNode(root);
}
private void printChildrenNode(Node node) {
//如果该节点是Element对象的话,则输出其Element名称,否则会输出#text
if (node instanceof Element) {
System.out.println("<"+node.getNodeName()+">");
}
NodeList list = node.getChildNodes();
for (int i = 0; i < list.getLength(); i++) {
Node childNode = list.item(i);
printChildrenNode(childNode);
}
}
//得到xml文档中标签属性的值: <product category="HandTool">
@Test
public void printTagAttr() throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse("WebRoot/product.xml");
String elementName = "product";
String elementAttrName = "plant";
Element element = (Element) document.getElementsByTagName(elementName).item(0);
String elementAttrValue = element.getAttribute(elementAttrName);
System.out.println("<"+elementName+" "+elementAttrName+"='"+elementAttrValue+"'>");
}
}
其中product.xml文件:
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE catalog SYSTEM "product.dtd"> <catalog id="cata1"> <product category="HandTool"> <specifications weight="2.0kg">扳手</specifications> <price street="香港街">80.0</price> <notes>这是扳手</notes> </product> <product category="Table"> <specifications>&table;</specifications> <price street="&street;" wholesale="部分">&price;</price> </product> </catalog> |
printTagName()方法的输出结果:
<catalog> <product> <specifications> <price> <notes> <product> <specifications> <price> |
<product category='HandTool'> |