2012軟考軟件設(shè)計(jì)師輔導(dǎo):java中xml解析器的應(yīng)用實(shí)例

字號(hào):

xml解析中,通常大家讀文件,解析的時(shí)候沒有問題,但是在寫文件的時(shí)候常常會(huì)碰到亂碼等問題,就我的個(gè)人體會(huì)是一般只要在寫文件的時(shí)候采用文件流的形式,設(shè)置好當(dāng)前的編碼方式,通常就會(huì)避免此類問題的發(fā)生!下面有兩個(gè)簡(jiǎn)單的分別是采用jdom和dom4j實(shí)現(xiàn)的例子:
    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;
    /**
    * Title:
    *
    * Description:
    *
    * Copyright: Copyright (c) 2005
    *
    * Company:
    *
    * @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(“l(fā)evel”, “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(“錄音機(jī)”);
    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();
    }
    }