xml格式化 java_Java XML格式化程序

女爷i 2023-02-28 06:10 72阅读 0赞

xml格式化 java

eXtensive Markup Language (XML) is one of the popular medium for messaging and communication between different applications. Since XML is open source and provides control over data format via DTD and XSDs, it’s widely used across technologies.

扩展标记语言(XML)是用于在不同应用程序之间进行消息传递和通信的流行媒介之一。 由于XML是开源的,并且可以通过DTD和XSD提供对数据格式的控制,因此XML在各种技术中得到了广泛使用。

Java XML格式化程序 (**Java XML Formatter**)

Few days back, I came across a situation where the third party API was returning Document object and XML message as String. So I wrote this simple XmlFormatter class to format the XML with proper indentation and convert Document object to XML String.

几天前,我遇到了这样一种情况,即第三方API正在将Document对象和XML消息返回为String。 因此,我编写了这个简单的XmlFormatter类,以使用适当的缩进来格式化XML,并将Document对象转换为XML String。

  1. package com.journaldev.java.xmlutil;
  2. import org.apache.xml.serialize.OutputFormat;
  3. import org.apache.xml.serialize.XMLSerializer;
  4. import org.w3c.dom.Document;
  5. import org.xml.sax.InputSource;
  6. import org.xml.sax.SAXException;
  7. import javax.xml.parsers.DocumentBuilder;
  8. import javax.xml.parsers.DocumentBuilderFactory;
  9. import javax.xml.parsers.ParserConfigurationException;
  10. import javax.xml.transform.OutputKeys;
  11. import javax.xml.transform.Transformer;
  12. import javax.xml.transform.TransformerFactory;
  13. import javax.xml.transform.dom.DOMSource;
  14. import javax.xml.transform.stream.StreamResult;
  15. import java.io.IOException;
  16. import java.io.StringReader;
  17. import java.io.StringWriter;
  18. import java.io.Writer;
  19. /**
  20. * Utility Class for formatting XML
  21. * @author Pankaj
  22. *
  23. */
  24. public class XmlFormatter {
  25. /**
  26. *
  27. * @param unformattedXml - XML String
  28. * @return Properly formatted XML String
  29. */
  30. public String format(String unformattedXml) {
  31. try {
  32. Document document = parseXmlFile(unformattedXml);
  33. OutputFormat format = new OutputFormat(document);
  34. format.setLineWidth(65);
  35. format.setIndenting(true);
  36. format.setIndent(2);
  37. Writer out = new StringWriter();
  38. XMLSerializer serializer = new XMLSerializer(out, format);
  39. serializer.serialize(document);
  40. return out.toString();
  41. } catch (IOException e) {
  42. e.printStackTrace();
  43. return "";
  44. }
  45. }
  46. /**
  47. * This function converts String XML to Document object
  48. * @param in - XML String
  49. * @return Document object
  50. */
  51. private Document parseXmlFile(String in) {
  52. try {
  53. DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  54. DocumentBuilder db = dbf.newDocumentBuilder();
  55. InputSource is = new InputSource(new StringReader(in));
  56. return db.parse(is);
  57. } catch (ParserConfigurationException e) {
  58. throw new RuntimeException(e);
  59. } catch (SAXException e) {
  60. throw new RuntimeException(e);
  61. } catch (IOException e) {
  62. e.printStackTrace();
  63. }
  64. return null;
  65. }
  66. /**
  67. * Takes an XML Document object and makes an XML String. Just a utility
  68. * function.
  69. *
  70. * @param doc - The DOM document
  71. * @return the XML String
  72. */
  73. public String makeXMLString(Document doc) {
  74. String xmlString = "";
  75. if (doc != null) {
  76. try {
  77. TransformerFactory transfac = TransformerFactory.newInstance();
  78. Transformer trans = transfac.newTransformer();
  79. trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
  80. trans.setOutputProperty(OutputKeys.INDENT, "yes");
  81. StringWriter sw = new StringWriter();
  82. StreamResult result = new StreamResult(sw);
  83. DOMSource source = new DOMSource(doc);
  84. trans.transform(source, result);
  85. xmlString = sw.toString();
  86. } catch (Exception e) {
  87. e.printStackTrace();
  88. }
  89. }
  90. return xmlString;
  91. }
  92. public static void main(String args[]){
  93. XmlFormatter formatter = new XmlFormatter();
  94. String book = "<?xml version=\"1.0\"?><catalog><book id=\"bk101\"><author>Gambardella, Matthew</author><title>XML Developers Guide</title><genre>Computer</genre><price>44.95</price><publish_date>2000-10-01</publish_date><description>An in-depth look at creating applications with XML.</description></book><book id=\"bk102\"><author>Ralls, Kim</author><title>Midnight Rain</title><genre>Fantasy</genre><price>5.95</price><publish_date>2000-12-16</publish_date><description>A former architect battles corporate zombies, an evil sorceress, and her own childhood to become queen of the world.</description></book></catalog>";
  95. System.out.println(formatter.format(book));
  96. }
  97. }

To use this class, you need Apache xercesImpl.jar that you can download from their website.

要使用此类,您需要Apache xercesImpl.jar ,您可以从其网站下载该类。

Output of the above class is a properly formatted XML String:

上面类的输出是格式正确的XML字符串:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <catalog>
  3. <book id="bk101">
  4. <author>Gambardella, Matthew</author>
  5. <title>XML Developers Guide</title>
  6. <genre>Computer</genre>
  7. <price>44.95</price>
  8. <publish_date>2000-10-01</publish_date>
  9. <description>An in-depth look at creating applications with XML.</description>
  10. </book>
  11. <book id="bk102">
  12. <author>Ralls, Kim</author>
  13. <title>Midnight Rain</title>
  14. <genre>Fantasy</genre>
  15. <price>5.95</price>
  16. <publish_date>2000-12-16</publish_date>
  17. <description>A former architect battles corporate zombies, an evil
  18. sorceress, and her own childhood to become queen of the world.</description>
  19. </book>
  20. </catalog>

I hope you will find this utility class helpful in formatting XML in Java and converting XML to Document and vice versa.

我希望您会发现该实用程序类有助于在Java中格式化XML并将XML转换为Document,反之亦然。

更新资料 (**Update**)

It’s been many years since I wrote this article, java has evolved a lot and we can format XML string easily using javax.xml.transform API.

自从我写这篇文章以来已经有很多年了,java已经发展了很多,我们可以使用javax.xml.transform API轻松格式化XML字符串。

  1. package com.journaldev.java.xmlutil;
  2. import java.io.StringReader;
  3. import java.io.StringWriter;
  4. import javax.xml.transform.OutputKeys;
  5. import javax.xml.transform.Source;
  6. import javax.xml.transform.Transformer;
  7. import javax.xml.transform.TransformerFactory;
  8. import javax.xml.transform.stream.StreamResult;
  9. import javax.xml.transform.stream.StreamSource;
  10. /**
  11. * Utility Class for formatting XML
  12. *
  13. * @author Pankaj
  14. *
  15. */
  16. public class XmlFormatter {
  17. public String format(String input) {
  18. return prettyFormat(input, "2");
  19. }
  20. public static String prettyFormat(String input, String indent) {
  21. Source xmlInput = new StreamSource(new StringReader(input));
  22. StringWriter stringWriter = new StringWriter();
  23. try {
  24. TransformerFactory transformerFactory = TransformerFactory.newInstance();
  25. Transformer transformer = transformerFactory.newTransformer();
  26. transformer.setOutputProperty(OutputKeys.INDENT, "yes");
  27. transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "yes");
  28. transformer.setOutputProperty("{https://xml.apache.org/xslt}indent-amount", indent);
  29. transformer.transform(xmlInput, new StreamResult(stringWriter));
  30. return stringWriter.toString().trim();
  31. } catch (Exception e) {
  32. throw new RuntimeException(e);
  33. }
  34. }
  35. public static void main(String args[]) {
  36. XmlFormatter formatter = new XmlFormatter();
  37. String book = "<?xml version=\"1.0\"?><catalog><book id=\"bk101\"><author>Gambardella, Matthew</author><title>XML Developers Guide</title><genre>Computer</genre><price>44.95</price><publish_date>2000-10-01</publish_date><description>An in-depth look at creating applications with XML.</description></book><book id=\"bk102\"><author>Ralls, Kim</author><title>Midnight Rain</title><genre>Fantasy</genre><price>5.95</price><publish_date>2000-12-16</publish_date><description>A former architect battles corporate zombies, an evil sorceress, and her own childhood to become queen of the world.</description></book></catalog>";
  38. System.out.println(formatter.format(book));
  39. }
  40. }

The output will be the same as earlier, you should use this instead of adding a dependency on any third party API.

输出将与之前的输出相同,您应该使用此输出,而不是添加对任何第三方API的依赖关系。

GitHub Repository. GitHub Repository下载示例代码。

翻译自: https://www.journaldev.com/71/java-xml-formatter

xml格式化 java

发表评论

表情:
评论列表 (有 0 条评论,72人围观)

还没有评论,来说两句吧...

相关阅读

    相关 xml格式化工具

      xml格式化工具提供了最简单的代码格式化功能,可以让编辑的代码得到优化,解决一些文本格式错误以及代码失效的问题,让你可以在编辑xml的时候优化源代码。xml格式化工具使用非

    相关 java xml格式化

      构建xml文档   所以我不能使用像XStream这样的XML序列化器:它将XML格式基于Java类。同样,像JAXB这样的Java XML绑定技术也不行,因为它从XML