Xml file generated by string xml

Source: Internet
Author: User

Xml file generated by string xml



/**
* Convert the xml of the string to the org. w3c. dom. Document Object.
* @ Param xml
* @ Return
*/
Public static Document getDocument (String xml ){
Document document = null;
Try {
DocumentBuilderFactory dbf = DocumentBuilderFactory. newInstance ();
DocumentBuilder db = dbf. newDocumentBuilder ();
InputStream is = new ByteArrayInputStream (xml. getBytes ());
Document = db. parse (is );
} Catch (Exception e ){
E. printStackTrace ();
}
Return document;
}
/**
* Write the org. w3c. dom. Document Object to the specified file.
*
* @ Param doc
* @ Param fileName
* @ Throws Exception
*/
Private static void outputXml (Document doc, String fileName ){
Try {
TransformerFactory tf = TransformerFactory. newInstance ();
Transformer transformer = tf. newTransformer ();
DOMSource source = new DOMSource (doc );
Transformer. setOutputProperty (OutputKeys. ENCODING, "UTF-8 ");
Transformer. setOutputProperty (OutputKeys. INDENT, "yes"); // adds line feed indentation, but the default indentation is 0.
Transformer. setOutputProperty ("{http://xml.apache.org/?t=indent-amount", "2"); // set indent to 2
PrintWriter pw = new PrintWriter (new OutputStreamWriter (new FileOutputStream (fileName), "UTF-8 ")));
StreamResult result = new StreamResult (pw );
Transformer. transform (source, result );
} Catch (Exception e ){
E. printStackTrace ();
}
}


Related Article

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.