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

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

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

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)


相关推荐

  • Win10总是开机黑屏?显卡驱动安装失败-驱动人生解决方案

    Win10总是开机黑屏?显卡驱动安装失败-驱动人生解决方案驱动人生了解到,自从win10系统发布以来,越来越多的用户都将系统给换成win10系统了。但是面对的用户基数大,系统难免会有不完善的地方。相信很多用户在使用过程中都会因为win10的各种毛病而被坑过,比如电脑开机就出现黑屏2分钟的问题。正常情况下,win10系统应该是开机后就可以显示的,不会出现需要黑屏2分钟左右的时间。这到底是哪里出现问题了呢?  经过驱动人生官方运维人员的检查发现,这个是因为Win10系统中潜在的一些bug导致的,如果大家的显卡有问题或者显卡驱动有问题,在开机后就会黑屏1-3分钟

  • python判断一个数是否为整数

    python判断一个数是否为整数原文:https://www.cnblogs.com/cepaAllium/p/11025877.html

  • 2. CMake 系列 – 编译多文件项目

    2. CMake 系列 – 编译多文件项目

    2021年11月22日
  • 经典算法–约瑟夫环问题的三种解法

    经典算法–约瑟夫环问题的三种解法约瑟夫环问题,这是一个很经典算法,处理的关键是:伪链表问题描述:N个人围成一圈,从第一个人开始报数,报到m的人出圈,剩下的人继续从1开始报数,报到m的人出圈;如此往复,直到所有人出圈。(模拟此过程,输出出圈的人的序号)在数据结构与算法书上,这个是用链表解决的。我感觉链表使用起来很麻烦,并且这个用链表处理起来也不是最佳的。我画了一个图用来理解:有如下问题需要首先考虑:1、“圈…

  • 图像处理入门教程[通俗易懂]

    图像处理入门教程[通俗易懂]  最近有人问我图像处理怎么研究,怎么入门,怎么应用,我竟一时语塞。仔细想想,自己也搞了两年图像方面的研究,做个两个创新项目,发过两篇论文,也算是有点心得,于是总结总结和大家分享,希望能对大家有所帮助。在写这篇教程之前我本想多弄点插图,让文章看起来花哨一点,后来我觉得没必要这样做,大家花时间沉下心来读读文字没什么不好,况且学术和技术本身也不是多么花哨的东西。  一、图像处理的应用  这个其实没什么…

  • 阿里云服务器开放某个端口失败_阿里云服务器怎么远程连接

    阿里云服务器开放某个端口失败_阿里云服务器怎么远程连接首先在防火墙开放端口,接着在Linux中开放,此处以8081为例因为centos7的防火墙iptables已经由firewalld来管理,所以需要将8080端口添加到防火墙开放端口firewall-cmd–zone=public–add-port=8081/tcp–permanent添加完端口之后,需要重启下防火墙systemctlrestartfirewalld.service查看端口是否添加到防火墙开放端口firewall-cmd–query-…

发表回复

您的电子邮箱地址不会被公开。

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