DOM:树结构 跨语言 不局限于Java 全程在内存中
SAX:事件驱动模式 省内存
JDOM: java常用解析xml的包 API相对友好
DOM4J:java常用解析xml的包 基于JDOM 性能方面也优秀 开源 推荐用此包
<!-- dom4j -->
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
package com.bc.mcode;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import org.dom4j.io.XMLWriter;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
public class Test {
private static class IgnoreDTDEntityResolver implements EntityResolver {
@Override
public InputSource resolveEntity(String publicId, String systemId)
throws SAXException, IOException {
return new InputSource(new ByteArrayInputStream("<?xml version='1.0' encoding='UTF-8'?>".getBytes()));
}
}
public static void main(String[] args) {
try {
SAXReader reader = new SAXReader();
reader.setEntityResolver(new IgnoreDTDEntityResolver()); // ignore dtd
// Document document = reader.read(new File("E:\\ccbckj\\download\\xml\\demo.xml")); // load
String str = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><!DOCTYPE cn-application-body SYSTEM \"/dtdandxsl/cn-application-body-20080416.dtd\">xxxx"; // 或者通过字符串加载
Document document = reader.read(new ByteArrayInputStream(str.getBytes(StandardCharsets.UTF_8))); // load
Element rootElement = document.getRootElement();
Iterator iterator = rootElement.elementIterator();
while (iterator.hasNext()){
Element item = (Element) iterator.next();
List<Attribute> attributes = item.attributes();
for (Attribute attribute : attributes) {
System.out.println("==>" + attribute.getValue());
}
Iterator iterator1 = item.elementIterator();
while (iterator1.hasNext()){
Element stuChild = (Element) iterator1.next();
System.out.println("节点名:"+stuChild.getName()+"---节点值:"+stuChild.getStringValue());
}
}
// 下面的参考代码是复制 这个xml为一个新的xml
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("UTF-8");
XMLWriter xmleriter = new XMLWriter(new FileOutputStream("E:\\ccbckj\\download\\temp\\c.xml"), format);
xmleriter.write(document);
xmleriter.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
网友评论