Java產生XML的縮排和換行__Java

來源:互聯網
上載者:User

一 DOM 以下代碼用DOM是產生一個XML文檔

package xml; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.w3c.dom.Element; public class XMLHandler { public void createXML() throws FileNotFoundException { Document doc = null; DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try { DocumentBuilder docBuilder = dbf.newDocumentBuilder(); doc = docBuilder.newDocument(); Element root = doc.createElement("root"); doc.appendChild(root); Element country = doc.createElement("contry"); country.appendChild(doc.createTextNode("China")); root.appendChild(country); Element city = doc.createElement("city"); city.appendChild(doc.createTextNode("Beijing")); country.appendChild(city); city = doc.createElement("city"); city.appendChild(doc.createTextNode("Shanghai")); country.appendChild(city); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); File file = new File("E://cities.xml"); FileOutputStream out = new FileOutputStream(file); StreamResult xmlResult = new StreamResult(out); transformer.transform(new DOMSource(doc), xmlResult); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (TransformerConfigurationException e) { e.printStackTrace(); } catch (TransformerException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); throw e; } } public static void main(String args[]) { XMLHandler xh = new XMLHandler(); try { xh.createXML(); } catch (FileNotFoundException e) { e.printStackTrace(); } } }

 

產生的xml如下
<?xml version="1.0" encoding="UTF-8"?><country><china><city>Beijing</city><city>Shanghai</city></china></country>

xml所有內容都在一行裡面,沒有換行和縮排

現在在代碼

Transformer transformer = tf.newTransformer();

後面加上

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

 

再次產生xml

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


這次有了換行,但是仍然沒有縮排。為此我尋找了多次google和百度都沒有找到解決方案,可能是有或者自己沒耐心,就想了辦法來處理。在前面加空格

Element.appendChild(doc.createTextNode("/n "));

最後代碼為

package xml; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.w3c.dom.Element; public class XMLHandler { public void createXML() throws FileNotFoundException { Document doc = null; DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try { DocumentBuilder docBuilder = dbf.newDocumentBuilder(); doc = docBuilder.newDocument(); Element country = doc.createElement("country"); doc.appendChild(country); country.appendChild(doc.createTextNode("/n ")); Element china = doc.createElement("china"); country.appendChild(china); china.appendChild(doc.createTextNode("/n ")); Element city = doc.createElement("city"); city.appendChild(doc.createTextNode("Beijing")); china.appendChild(city); china.appendChild(doc.createTextNode("/n ")); city = doc.createElement("city"); city.appendChild(doc.createTextNode("Shanghai")); china.appendChild(city); china.appendChild(doc.createTextNode("/n ")); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); File file = new File("E://cities.xml"); FileOutputStream out = new FileOutputStream(file); StreamResult xmlResult = new StreamResult(out); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.transform(new DOMSource(doc), xmlResult); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (TransformerConfigurationException e) { e.printStackTrace(); } catch (TransformerException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); throw e; } } public static void main(String args[]) { XMLHandler xh = new XMLHandler(); try { xh.createXML(); } catch (FileNotFoundException e) { e.printStackTrace(); } } }

最終產生的xml為

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

 

二 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>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.