Java generates XML indentation and newline __java

Source: Internet
Author: User

One DOM The following code uses the DOM to generate an XML document

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 ("the"); 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.printSt Acktrace (); 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 (FileNotFound Exception e) {e.printstacktrace ();}} }

The generated XML is as follows
<?xml version= "1.0" encoding= "UTF-8"? ><country><china><city>beijing</city><city >Shanghai</city></china></country>

All XML content is on one line, without wrapping and indenting

Now in the code

Transformer Transformer = Tf.newtransformer ();

Add it back.

Transformer.setoutputproperty (outputkeys.indent, "yes");

Generate XML again

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


This time there was a line break, but still no indentation. For this I looked for a number of times Google and Baidu did not find a solution, may have or their own impatience, think of ways to deal with. Add a space to the front

Element.appendchild (Doc.createtextnode ("n"));

The last code is

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-Doc.createelement ("a"); Country.appendchild (a); 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.printSt Acktrace (); 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 (Filenotfoundexce Ption e) {e.printstacktrace ();}} }

The resulting XML is

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

Two sax generates XML with sax and wraps line indents

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 ("", "", "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 ("", "", "a"); Th.endelement ("", "", "country"); Th.enddocument (); Xmlstr = Writerstr.getbuffer (). toString (); catch (Transformerconfigurationexception e) {e.printstacktrace ();} catch (Saxexception e) {e.printstacktrace ();} cat CH (Exception e) {e.printstacktrace ();} return xmlstr; public static void Main (String args[]) {Xmlhandler XH = new Xmlhandler (); Xh.createxmlfile ();}}

The XML generated with Sax is as follows

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

Also no line wrapping and indentation

Add in Code

Transformer.setoutputproperty (outputkeys.indent, "yes");

The resulting XML has a newline but is still not indented

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

Also follow the methods in the DOM and add spaces

String four = "n"; Transformerhandler.characters (Four.tochararray (), 0,four.length ());

The final Sax code is as follows:

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 ("", "", "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 ("", "", "a"); Th.endelement ("", "", "country"); Th.enddocument (); Xmlstr = Writerstr.getbuffer (). toString (); catch (Transformerconfigurationexception e) {e.printstacktrace ();} catch (Saxexception e) {e.printstacktrace ();} cat CH (Exception e) {e.printstacktrace ();} returnXMLSTR; public static void Main (String args[]) {Xmlhandler XH = new Xmlhandler (); Xh.createxmlfile ();}}

The generated XML

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.