转自:https://blog.csdn.net/wmyasw/article/details/8686420

package com.mymhotel.opera;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Properties;

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

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class DOMUtils {
/**
* 初始化一个空Document对象返回。
*
* @return a Document
*/
public static Document newXMLDocument() {
try {
return newDocumentBuilder().newDocument();
} catch (ParserConfigurationException e) {
throw new RuntimeException(e.getMessage());
}
}

/**
* 初始化一个DocumentBuilder
*
* @return a DocumentBuilder
* @throws ParserConfigurationException
*/
public static DocumentBuilder newDocumentBuilder()
throws ParserConfigurationException {
return newDocumentBuilderFactory().newDocumentBuilder();
}

/**
* 初始化一个DocumentBuilderFactory
*
* @return a DocumentBuilderFactory
*/
public static DocumentBuilderFactory newDocumentBuilderFactory() {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
return dbf;
}

/**
* 将传入的一个XML String转换成一个org.w3c.dom.Document对象返回。
*
* @param xmlString
* 一个符合XML规范的字符串表达。
* @return a Document
*/
public static Document parseXMLDocument(String xmlString) {
if (xmlString == null) {
throw new IllegalArgumentException();
}
try {
return newDocumentBuilder().parse(
new InputSource(new StringReader(xmlString)));
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}

/**
* 给定一个输入流,解析为一个org.w3c.dom.Document对象返回。
*
* @param input
* @return a org.w3c.dom.Document
*/
public static Document parseXMLDocument(InputStream input) {
if (input == null) {
throw new IllegalArgumentException("参数为null!");
}
try {
return newDocumentBuilder().parse(input);
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}

/**
* 给定一个文件名,获取该文件并解析为一个org.w3c.dom.Document对象返回。
*
* @param fileName
* 待解析文件的文件名
* @return a org.w3c.dom.Document
*/
public static Document loadXMLDocumentFromFile(String fileName) {
if (fileName == null) {
throw new IllegalArgumentException("未指定文件名及其物理路径!");
}
try {
return newDocumentBuilder().parse(new File(fileName));
} catch (SAXException e) {
throw new IllegalArgumentException("目标文件(" + fileName
+ ")不能被正确解析为XML!" + e.getMessage());
} catch (IOException e) {
throw new IllegalArgumentException("不能获取目标文件(" + fileName + ")!"
+ e.getMessage());
} catch (ParserConfigurationException e) {
throw new RuntimeException(e.getMessage());
}
}

/*
* 把dom文件转换为xml字符串
*/
public static String toStringFromDoc(Document document) {
String result = null;

if (document != null) {
StringWriter strWtr = new StringWriter();
StreamResult strResult = new StreamResult(strWtr);
TransformerFactory tfac = TransformerFactory.newInstance();
try {
javax.xml.transform.Transformer t = tfac.newTransformer();
t.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
t.setOutputProperty(OutputKeys.INDENT, "yes");
t.setOutputProperty(OutputKeys.METHOD, "xml"); // xml, html,
// text
t.setOutputProperty(
"{http://xml.apache.org/xslt}indent-amount", "4");
t.transform(new DOMSource(document.getDocumentElement()),
strResult);
} catch (Exception e) {
System.err.println("XML.toString(Document): " + e);
}
result = strResult.getWriter().toString();
try {
strWtr.close();
} catch (IOException e) {
e.printStackTrace();
}
}

return result;
}

/**
* 给定一个节点,将该节点加入新构造的Document中。
*
* @param node
* a Document node
* @return a new Document
*/

public static Document newXMLDocument(Node node) {
Document doc = newXMLDocument();
doc.appendChild(doc.importNode(node, true));
return doc;
}

/**
* 将传入的一个DOM Node对象输出成字符串。如果失败则返回一个空字符串""。
*
* @param node
* DOM Node 对象。
* @return a XML String from node
*/

/*
* public static String toString(Node node) { if (node == null) { throw new
* IllegalArgumentException(); } Transformer transformer = new
* Transformer(); if (transformer != null) { try { StringWriter sw = new
* StringWriter(); transformer .transform(new DOMSource(node), new
* StreamResult(sw)); return sw.toString(); } catch (TransformerException
* te) { throw new RuntimeException(te.getMessage()); } } return ""; }
*/

/**
* 将传入的一个DOM Node对象输出成字符串。如果失败则返回一个空字符串""。
*
* @param node
* DOM Node 对象。
* @return a XML String from node
*/

/*
* public static String toString(Node node) { if (node == null) { throw new
* IllegalArgumentException(); } Transformer transformer = new
* Transformer(); if (transformer != null) { try { StringWriter sw = new
* StringWriter(); transformer .transform(new DOMSource(node), new
* StreamResult(sw)); return sw.toString(); } catch (TransformerException
* te) { throw new RuntimeException(te.getMessage()); } } return ""; }
*/

/**
* 获取一个Transformer对象,由于使用时都做相同的初始化,所以提取出来作为公共方法。
*
* @return a Transformer encoding gb2312
*/

public static Transformer newTransformer() {
try {
Transformer transformer = TransformerFactory.newInstance()
.newTransformer();
Properties properties = transformer.getOutputProperties();
properties.setProperty(OutputKeys.ENCODING, "gb2312");
properties.setProperty(OutputKeys.METHOD, "xml");
properties.setProperty(OutputKeys.VERSION, "1.0");
properties.setProperty(OutputKeys.INDENT, "no");
transformer.setOutputProperties(properties);
return transformer;
} catch (TransformerConfigurationException tce) {
throw new RuntimeException(tce.getMessage());
}
}

/**
* 返回一段XML表述的错误信息。提示信息的TITLE为:系统错误。之所以使用字符串拼装,主要是这样做一般 不会有异常出现。
*
* @param errMsg
* 提示错误信息
* @return a XML String show err msg
*/
/*
* public static String errXMLString(String errMsg) { StringBuffer msg = new
* StringBuffer(100);
* msg.append("<?xml version="1.0" encoding="gb2312" ?>");
* msg.append("<errNode title="系统错误" errMsg="" + errMsg + ""/>"); return
* msg.toString(); }
*/
/**
* 返回一段XML表述的错误信息。提示信息的TITLE为:系统错误
*
* @param errMsg
* 提示错误信息
* @param errClass
* 抛出该错误的类,用于提取错误来源信息。
* @return a XML String show err msg
*/
/*
* public static String errXMLString(String errMsg, Class errClass) {
* StringBuffer msg = new StringBuffer(100);
* msg.append("<?xml version='1.0' encoding='gb2312' ?>");
* msg.append("<errNode title="
* 系统错误" errMsg=""+ errMsg + "" errSource=""+ errClass.getName()+ ""/>");
*  return msg.toString(); }
*/
/**
* 返回一段XML表述的错误信息。
*
* @param title
* 提示的title
* @param errMsg
* 提示错误信息
* @param errClass
* 抛出该错误的类,用于提取错误来源信息。
* @return a XML String show err msg
*/

public static String errXMLString(String title, String errMsg,
Class errClass) {
StringBuffer msg = new StringBuffer(100);
msg.append("<?xml version='1.0' encoding='utf-8' ?>");
msg.append("<errNode title=" + title + "errMsg=" + errMsg
+ "errSource=" + errClass.getName() + "/>");
return msg.toString();
}

}

————————————————
版权声明:本文为CSDN博主「wmyasw」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/wmyasw/article/details/8686420

org.w3c.dom document 和xml 字符串 互转的更多相关文章

  1. org.w3c.dom.Document 与org.dom4j.Document互转

    public static Document parse(org.w3c.dom.Document doc) throws Exception { if (doc == null) { return ...

  2. cxf 报错:java.lang.NoSuchMethodError: org.apache.ws.commons.schema.XmlSchemaCollection.read(Lorg/w3c/dom/Document;Ljava/lang/String;)

    由于没有仔细查看官方提供的文档,由jdk版本不一致导致的出错: http://cxf.apache.org/cxf-316-release-notes.html 自己使用的是jdk1.8. 报Exce ...

  3. [ java 工具类] xml字符串解析成Map(DOM解析)

    package com.tencent.jungle.wechat.util; import com.google.inject.Singleton; import org.w3c.dom.Docum ...

  4. org.w3c.dom(java dom)解析XML文档

    位于org.w3c.dom操作XML会比较简单,就是将XML看做是一颗树,DOM就是对这颗树的一个数据结构的描述,但对大型XML文件效果可能会不理想 首先来了解点Java DOM 的 API:1.解析 ...

  5. org.w3c.dom。 XML解析 练习

    HTML文档 1 import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; ...

  6. 精讲 org.w3c.dom(java dom)解析XML文档

    org.w3c.dom(java dom)解析XML文档 位于org.w3c.dom操作XML会比较简单,就是将XML看做是一颗树,DOM就是对这颗树的一个数据结构的描述,但对大型XML文件效果可能会 ...

  7. java解析xml字符串方法

    一,用DOM4J  针对无重复标签的xml字符串格式,如下: 针对此种情况可用DOM4J解析法,引入 dom4j的相关jar包代码如下: Document document=DocumentHelpe ...

  8. xml转Map,对象,Map转xml,inputs tram 转xml 字符串的工具类方法

    众所周知,大家在微信开发工程中,由于微信开发文档中,对于消息的接收发送都是基础xml数据的(太坑了),所以我们需要对XML进行解析转换: 1.我们先引入所需要的依赖 dom4j (解析xml的),xs ...

  9. javaxml文件基础:Dom怎么生成xml文件

    package CreateXmlByDom; import java.io.File; import javax.xml.parsers.DocumentBuilder; import javax. ...

随机推荐

  1. skywalking安装运行(docker)

    https://github.com/apache/skywalking-docker/tree/master/6/6.5 https://hub.docker.com/r/apache/skywal ...

  2. 工具系列 | 使用Lodop进行WEB打印程序开发

    Lodop(标音:劳道谱,俗称:露肚皮)是专业WEB控件,用它既可裁剪输出页面内容,又可用程序代码直接实现 复杂打印.控件功能强大,却简单易用,所有调用如同JavaScript扩展语句. WEB套打可 ...

  3. 在本地搭建hyperledger fabric 网络

    参考了官方文档,直接就可以了https://hyperledger-fabric.readthedocs.io/en/latest/build_network.html 很好用 ➜ ~ cd $GOP ...

  4. android -------- DES加密解密算法

    DES全称为Data Encryption Standard,即数据加密标准,是一种使用密钥加密的块算法,1977年被美国联邦政府的国家标准局确定为联邦资料处理标准(FIPS),并授权在非密级政府通信 ...

  5. Activiti6 应用安装 activiti-admin,activiti-app,activiti-rest

    activiti6安装包中 1/直接将三个war包放入tomcat中,即可运行,使用H2内存数据库 2/使用mysql数据库运行 2.1/activiti-admin # security confi ...

  6. asp.net core mvc 读取配置文件appsettings.json

    上一篇我们将了读取自定义配置文件.这篇我们讲一下asp.net core mvc里读取自带的配置文件 appsettings.json 首先创建个asp.net core mvc项目,项目里有Prog ...

  7. Java12新特性 -- Shenandoah GC

    Shenandoah 垃圾回收器是 Red Hat 在 2014 年宣布进行的一项垃圾收集器研究项目 Pauseless GC 的实现,旨在针对 JVM 上的内存收回实现低停顿的需求.该设计将与应用程 ...

  8. [LeetCode] 203. Remove Linked List Elements 移除链表元素

    Remove all elements from a linked list of integers that have value val. ExampleGiven: 1 --> 2 --& ...

  9. intellij idea搭建SpringBoot

    1.安装mavn在settings.xml设置下载链接 <mirror> <id>nexus-aliyun</id> <mirrorOf>*,!jeec ...

  10. 一键安装docker-ce

    curl https://get.docker.com |env CHANNEL=stable sudo sh -s docker --mirror Aliyun