Java生成XML的缩进和换行SAX

Java生成XML的缩进和换行SAX
2010-04-26 13:51

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/zxcvbnmluton/archive/2010/04/26/5528747.aspx

二 SAX 用SAX生成xml并换行缩进

package xml;

import java.io.FileOutputStream;
import java.io.StringWriter;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamResult;

import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;

public class XMLHandler {

public String createXMLFile() {
   String xmlStr = null;
   try {
    Result resultXml = new StreamResult(new FileOutputStream("E://cities.xml"));
    StringWriter writerStr = new StringWriter();
    SAXTransformerFactory sff = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
    TransformerHandler th = sff.newTransformerHandler();
    Transformer transformer = th.getTransformer();
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");   
    th.setResult(resultXml);
    th.startDocument();
    AttributesImpl attr = new AttributesImpl();
    th.startElement("", "", "country", attr);
    th.startElement("", "", "china", attr);

    th.startElement("", "", "city", attr);
    String bj = "Beijing";
    th.characters(bj.toCharArray(), 0, bj.length());
    th.endElement("", "", "city");

    th.startElement("", "", "city", attr);
    String sh = "Shanghai";
    th.characters(sh.toCharArray(), 0, sh.length());
    th.endElement("", "", "city");

    th.endElement("", "", "china");
    th.endElement("", "", "country");
    th.endDocument();
    xmlStr = writerStr.getBuffer().toString();
   } catch (TransformerConfigurationException e) {
    e.printStackTrace();
   } catch (SAXException e) {
    e.printStackTrace();
   } catch (Exception e) {
    e.printStackTrace();
   }
   return xmlStr;
}

public static void main(String args[]) {
   XMLHandler xh = new XMLHandler();
   xh.createXMLFile();
}
}

用SAX生成的xml如下

<?xml version="1.0" encoding="UTF-8"?><country><china><city>Beijing</city><city>Shanghai</city></china></country>

同样没有换行和缩进

在代码中增加

transformer.setOutputProperty(OutputKeys.INDENT, "yes");

后生成的xml有了换行但仍没有缩进

<?xml version="1.0" encoding="UTF-8"?>
<country>
<china>
<city>Beijing</city>
<city>Shanghai</city>
</china>
</country>

同样按照DOM中的方法加空格

String four = "\n    ";
TransformerHandler.characters(four.toCharArray(),0,four.length());

最终SAX代码如下:

package xml;

import java.io.FileOutputStream;
import java.io.StringWriter;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamResult;

import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;

public class XMLHandler {

public String createXMLFile() {
   String xmlStr = null;
   try {
    Result resultXml = new StreamResult(new FileOutputStream("E://cities.xml"));
    StringWriter writerStr = new StringWriter();
    SAXTransformerFactory sff = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
    TransformerHandler th = sff.newTransformerHandler();
    Transformer transformer = th.getTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");   
    th.setResult(resultXml);
    th.startDocument();
    String four = "\n    ";
    String eight = "\n        ";
    AttributesImpl attr = new AttributesImpl();
   
    th.startElement("", "", "country", attr);
   
    th.characters(four.toCharArray(),0,four.length());
   
    th.startElement("", "", "china", attr);
   
    th.characters(eight.toCharArray(),0,eight.length());

    th.startElement("", "", "city", attr);
    String bj = "Beijing";
    th.characters(bj.toCharArray(), 0, bj.length());
    th.endElement("", "", "city");

    th.characters(eight.toCharArray(),0,eight.length());
   
    th.startElement("", "", "city", attr);
    String sh = "Shanghai";
    th.characters(sh.toCharArray(), 0, sh.length());
    th.endElement("", "", "city");

    th.characters(four.toCharArray(),0,four.length());
   
    th.endElement("", "", "china");
    th.endElement("", "", "country");
    th.endDocument();
    xmlStr = writerStr.getBuffer().toString();
   } catch (TransformerConfigurationException e) {
    e.printStackTrace();
   } catch (SAXException e) {
    e.printStackTrace();
   } catch (Exception e) {
    e.printStackTrace();
   }
   return xmlStr;
}

public static void main(String args[]) {
   XMLHandler xh = new XMLHandler();
   xh.createXMLFile();
}
}

生成的XML

<?xml version="1.0" encoding="UTF-8"?>
<country>
    <china>
        <city>Beijing</city>
        <city>Shanghai</city>
    </china>
</country>

 

使用SAXJava生成XML的步骤如下: 1. 创建一个 SAXParserFactory 实例并且用它来创建一个 SAXParser 对象。 2. 创建一个 DefaultHandler 的子类实例。 3. 调用 SAXParser 的 parse() 方法,并将 XML 文件名和 DefaultHandler 子类实例作为参数传入。 下面是一个使用 SAXJava 创建 XML 文件的示例代码: ```java import javax.xml.parsers.*; import org.xml.sax.*; import org.xml.sax.helpers.*; import java.io.*; public class CreateXMLWithSAX { public static void main(String[] args) throws Exception { // 创建 SAXParserFactory 和 SAXParser 对象 SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser = factory.newSAXParser(); // 创建 DefaultHandler 的子类实例 MyHandler handler = new MyHandler(); // 调用 parse() 方法解析 XML 文件 saxParser.parse(new File("students.xml"), handler); } } class MyHandler extends DefaultHandler { // 重写 startDocument() 方法 public void startDocument() throws SAXException { System.out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); System.out.println("<students>"); } // 重写 startElement() 方法 public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { System.out.print("<" + qName); for (int i = 0; i < attributes.getLength(); i++) { System.out.print(" " + attributes.getQName(i) + "=\"" + attributes.getValue(i) + "\""); } System.out.print(">"); } // 重写 characters() 方法 public void characters(char[] ch, int start, int length) throws SAXException { System.out.print(new String(ch, start, length)); } // 重写 endElement() 方法 public void endElement(String uri, String localName, String qName) throws SAXException { System.out.print("</" + qName + ">"); } // 重写 endDocument() 方法 public void endDocument() throws SAXException { System.out.println("</students>"); } } ``` 这个示例程序会读取名为 "students.xml" 的 XML 文件,并将其转化为以下格式的 XML: ```xml <?xml version="1.0" encoding="UTF-8"?> <students> <student id="1001">Tom</student> <student id="1002">Jerry</student> <student id="1003">Mike</student> </students> ``` 注意:这个示例程序中,MyHandler 类继承了 DefaultHandler 类,并且重写了其中的方法,这些方法会在 SAX 解析过程中被调用。在这些方法中,我们可以根据需要对 XML 文件进行处理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值