xml格式化 java_Java XML格式化程序

xml格式化 java_Java XML格式化程序xml格式化javaeXtensiveMarkupLanguage(XML)isoneofthepopularmediumformessagingandcommunicationbetweendifferentapplications.SinceXMLisopensourceandprovidescontroloverdataformatv…

大家好,又见面了,我是你们的朋友全栈君。

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。

package com.journaldev.java.xmlutil;

import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.XMLSerializer;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

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.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;

/**
 * Utility Class for formatting XML
 * @author Pankaj
 *
 */
public class XmlFormatter {

	/**
	 *
	 * @param unformattedXml - XML String
	 * @return Properly formatted XML String
	 */
	public String format(String unformattedXml) {
		try {
			Document document = parseXmlFile(unformattedXml);

			OutputFormat format = new OutputFormat(document);
			format.setLineWidth(65);
			format.setIndenting(true);
			format.setIndent(2);
			Writer out = new StringWriter();
			XMLSerializer serializer = new XMLSerializer(out, format);
			serializer.serialize(document);

			return out.toString();
		} catch (IOException e) {
			e.printStackTrace();
			return "";
		}

	}

	/**
	 * This function converts String XML to Document object
	 * @param in - XML String
	 * @return Document object
	 */
	private Document parseXmlFile(String in) {
		try {
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			InputSource is = new InputSource(new StringReader(in));
			return db.parse(is);
		} catch (ParserConfigurationException e) {
			throw new RuntimeException(e);
		} catch (SAXException e) {
			throw new RuntimeException(e);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	/**
	 * Takes an XML Document object and makes an XML String. Just a utility
	 * function.
	 *
	 * @param doc - The DOM document
	 * @return the XML String
	 */
	public String makeXMLString(Document doc) {
		String xmlString = "";
		if (doc != null) {
			try {
				TransformerFactory transfac = TransformerFactory.newInstance();
				Transformer trans = transfac.newTransformer();
				trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
				trans.setOutputProperty(OutputKeys.INDENT, "yes");
				StringWriter sw = new StringWriter();
				StreamResult result = new StreamResult(sw);
				DOMSource source = new DOMSource(doc);
				trans.transform(source, result);
				xmlString = sw.toString();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return xmlString;
	}
	public static void main(String args[]){
		XmlFormatter formatter = new XmlFormatter();
		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>";
		System.out.println(formatter.format(book));
	}
}

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字符串:

<?xml version="1.0" encoding="UTF-8"?>
<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>

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字符串。

package com.journaldev.java.xmlutil;

import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

/**
 * Utility Class for formatting XML
 * 
 * @author Pankaj
 *
 */
public class XmlFormatter {

	public String format(String input) {
		return prettyFormat(input, "2");
	}

	public static String prettyFormat(String input, String indent) {
		Source xmlInput = new StreamSource(new StringReader(input));
		StringWriter stringWriter = new StringWriter();
		try {
			TransformerFactory transformerFactory = TransformerFactory.newInstance();
			Transformer transformer = transformerFactory.newTransformer();
			transformer.setOutputProperty(OutputKeys.INDENT, "yes");
			transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "yes");
			transformer.setOutputProperty("{https://xml.apache.org/xslt}indent-amount", indent);
			transformer.transform(xmlInput, new StreamResult(stringWriter));

			return stringWriter.toString().trim();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static void main(String args[]) {
		XmlFormatter formatter = new XmlFormatter();
		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>";
		System.out.println(formatter.format(book));
	}
}

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

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/160132.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 数字电路期末课程设计总结(一)「建议收藏」

    数字电路期末课程设计总结(一)「建议收藏」嗯。学完数字电路,期末老师布置了几个FPGA题目选择完成,时间为两星期。我把几道题整合了一下,做了个小系统,还挺好玩的。两个星期的时间很短,越到后期感觉越疲惫,注意力开始发散,效率也逐渐下滑,还好坚持

    2022年8月5日
    3
  • linux虚拟机设置固定IP

    linux虚拟机设置固定IPlinux虚拟机设置固定IPubuntu虚拟机(桥接模式)设置固定IP方法很简单,直接在系统设置里面配置就可以了1.先使用ifconfig查看掩码2.点击设置3.点击network再点击set4.第一个为虚拟机ip,为避免冲突,建议设置210以上的ip5.重启,ifconfig查看ip不同版本系统界面可能不同,但操作类似…

    2022年7月16日
    10
  • Hadoop 生态系统的构成(Hadoop 生态系统组件释义)

    Hadoop 生态系统的构成(Hadoop 生态系统组件释义)现在先让我们了解一下Hadoop生态系统的构成,主要认识Hadoop生态系统都包括那些子项目,每个项目都有什么特点,每个项目都能解决哪一类问题,能回答这三个问题就可以了(本段属于热身…重在理解Hadoop生态系统组成,现状,发展,将来)。HDFS:HDFS(HadoopDistributedFileSystem,Hadoop分布式文件系统)是Hadoop体系中数据存储管理的基础。它是一个高度容错的系统,能检测和应对硬件故障,用于在低成本的通用硬件上运行。HDFS简化了文件的一致性模

    2022年5月12日
    36
  • 使用 BasePage 来解决 GridView 执行 RenderControl 产生的错误

    使用 BasePage 来解决 GridView 执行 RenderControl 产生的错误摘要GridView控件常有需要汇出Excel的需求,一般都是将GridView使用RenderControl来输出其HTML程序代码。本文即在讨论RenderControl所产生的问题及解决方式,不过本文是透过BasePage的方式,让RenderControl的相关处理动作更简化。手动解决RenderControl所产生的问题下面的Contr…

    2022年7月20日
    12
  • executescalar mysql_ExecuteScalar()

    executescalar mysql_ExecuteScalar()ExecuteScalar()方法的作用是:执行查询,并返回查询所返回的结果集中第一行的第一列。所有其他的列和行将被忽略。它的返回值时object,若是想判断某条数据在数据库里存不存在便可使用该方法,//sql文privatestringm_str_variationInfo=@”SELECTvariationinfoMngnoFROMsellersandvariationmngtbl…

    2022年6月15日
    27
  • 用html编写或在dw中完成,Dreamweaver教程-在 Dreamweaver 中编写 HTML 代码[通俗易懂]

    用html编写或在dw中完成,Dreamweaver教程-在 Dreamweaver 中编写 HTML 代码[通俗易懂]Dreamweaver教程-在Dreamweaver中编写HTML代码,代码,教程,标签,光标,文本Dreamweaver教程-在Dreamweaver中编写HTML代码易采站长站,站长之家为您整理了Dreamweaver教程-在Dreamweaver中编写HTML代码的相关内容。1.启动DreamweaverCS52.点击左上角的“文件”>“新建”。3.在“新…

    2022年5月2日
    41

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号