java中xml解析器的应用实例
1、dom4j
package org.lyj.xml;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import org.dom4j.Document;
import org.dom4j.Element;
import java.io.FileWriter;
import org.dom4j.io.OutputFormat;
import org.dom4j.Namespace;
import org.dom4j.io.XMLWriter;
import java.io.File;
import java.io.IOException;
import org.dom4j.DocumentHelper;
/**
* <p>Title: </p>
*
* <p>Description: </p>
*
* <p>Copyright: Copyright (c) 2005</p>
*
* <p>Company: </p>
*
* @author not attributable
* @version 1.0
*/
public class Dom4jTest {
public void generateDocument() {
org.dom4j.DocumentFactory df = new org.dom4j.DocumentFactory();
Document document = df.createDocument();//.createDocument();
Element catalogElement = document.addElement("catalog");
catalogElement.addComment("An XML Catalog");
catalogElement.addProcessingInstruction("target", "text");
Element journalElement = catalogElement.addElement("journal");
journalElement.addAttribute("title", "XML Zone");
journalElement.addAttribute("publisher", "IBM developerWorks");
Element articleElement = journalElement.addElement("article");
articleElement.addAttribute("level", "Intermediate");
articleElement.addAttribute("date", "December-2001");
Element titleElement = articleElement.addElement("title");
titleElement.setText("Java configuration with XML Schema");
Element authorElement = articleElement.addElement("author");
Element firstNameElement = authorElement.addElement("录音机");
firstNameElement.setText("Marcello");
Element lastNameElement = authorElement.addElement("刘");
lastNameElement.setText("Vitaletti");
document.addDocType("catalog",
null, "file://c:/Dtds/catalog.dtd");
document.setXMLEncoding("gb2312");
try {
OutputFormat of = OutputFormat.createCompactFormat();
of.setEncoding("gb2312");
XMLWriter output = new XMLWriter(
new java.io.FileOutputStream(new File("c:/catalog/catalog.xml")),of);
output.write(document);
output.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
public static void main(String[] argv) {
Dom4jTest dom4j = new Dom4jTest();
dom4j.generateDocument();2、jdom
package org.lyj.xml;
import org.jdom.output.Format;
import org.jdom.Document;
import java.io.IOException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
import org.jdom.JDOMException;
/**
* <p>Title: </p>
*
* <p>Description: </p>
*
* <p>Copyright: Copyright (c) 2005</p>
*
* <p>Company: </p>
*
* @author not attributable
* @version 1.0
*/
public class JdomWriter {
public JdomWriter() {
}
public void write(){
try {
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build("aa.xml");
XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat()。setEncoding("utf-8"));
outputter.output(doc, new java.io.FileOutputStream("bb.xml"));
} catch (JDOMException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String args[]){
JdomWriter jd = new JdomWriter();
jd.write();
}
}