1.Dom解析XML
package com.fjh.xml;
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.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class DomParseXml {
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse("product.xml");
System.out.println(document.getElementsByTagName("products"));
Node products = document.getElementsByTagName("products").item(0);
NodeList childNodes = products.getChildNodes();
System.out.println(childNodes.getLength());
for(int index = 0; index < childNodes.getLength(); index ++) {
Node node = childNodes.item(index);
if(node.getNodeType() == Node.ELEMENT_NODE) {
Node namedItem = node.getAttributes().getNamedItem("num");
String nodeValue = namedItem.getNodeValue();
System.out.println(nodeValue);
NodeList childNodes2 = node.getChildNodes();
for(int i = 0; i < childNodes2.getLength(); i ++) {
Node item = childNodes2.item(i);
System.out.println( "节点的名称 "+ item.getNodeName());
System.out.println( "节点的类型 "+ item.getNodeType());
System.out.println( "节点的值 "+ item.getTextContent());
}
}
}
}
}
2.Dom4j
package com.fjh.xml;
import java.io.File;
import java.util.Iterator;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class Dom4jParseXml {
public static void parse(String fileName) throws DocumentException {
SAXReader reader = new SAXReader();
Document document = reader.read(new File(fileName));
Element rootElement = document.getRootElement();
System.out.println(rootElement.getName());
for(Iterator<Element> it = rootElement.elementIterator(); it.hasNext();) {
Element product = it.next();
System.out.println("获取属性的值" + product.attributeValue("num"));
for(Iterator<Element> it2 = product.elementIterator(); it2.hasNext();) {
Element item = it2.next();
System.out.println("获取节点的名称:" + item.getName() + " 节点的值:" + item.getStringValue());
}
}
}
public static void main(String[] args) throws DocumentException {
parse("product.xml");
}
}