博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
xml格式化 java_Java XML格式化程序
阅读量:2529 次
发布时间:2019-05-11

本文共 7353 字,大约阅读时间需要 24 分钟。

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 = "
Gambardella, Matthew
XML Developers Guide
Computer
44.95
2000-10-01
An in-depth look at creating applications with XML.
Ralls, Kim
Midnight Rain
Fantasy
5.95
2000-12-16
A former architect battles corporate zombies, an evil sorceress, and her own childhood to become queen of the world.
"; 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字符串:

Gambardella, Matthew
XML Developers Guide
Computer
44.95
2000-10-01
An in-depth look at creating applications with XML.
Ralls, Kim
Midnight Rain
Fantasy
5.95
2000-12-16
A former architect battles corporate zombies, an evil sorceress, and her own childhood to become queen of the world.

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 = "
Gambardella, Matthew
XML Developers Guide
Computer
44.95
2000-10-01
An in-depth look at creating applications with XML.
Ralls, Kim
Midnight Rain
Fantasy
5.95
2000-12-16
A former architect battles corporate zombies, an evil sorceress, and her own childhood to become queen of the world.
"; 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的依赖关系。

. 下载示例代码。

翻译自:

xml格式化 java

转载地址:http://oaozd.baihongyu.com/

你可能感兴趣的文章
Hdu【线段树】基础题.cpp
查看>>
时钟系统
查看>>
BiTree
查看>>
5个基于HTML5的加载动画推荐
查看>>
水平权限漏洞的修复方案
查看>>
静态链接与动态链接的区别
查看>>
Android 关于悬浮窗权限的问题
查看>>
如何使用mysql
查看>>
linux下wc命令详解
查看>>
敏捷开发中软件测试团队的职责和产出是什么?
查看>>
在mvc3中使用ffmpeg对上传视频进行截图和转换格式
查看>>
python的字符串内建函数
查看>>
Spring - DI
查看>>
微软自己的官网介绍 SSL 参数相关
查看>>
Composite UI Application Block (CAB) 概念和术语
查看>>
ajax跨域,携带cookie
查看>>
阶段3 2.Spring_01.Spring框架简介_03.spring概述
查看>>
阶段3 2.Spring_02.程序间耦合_1 编写jdbc的工程代码用于分析程序的耦合
查看>>
阶段3 2.Spring_01.Spring框架简介_04.spring发展历程
查看>>
阶段3 2.Spring_02.程序间耦合_3 程序的耦合和解耦的思路分析1
查看>>