org.w3c.dom document 和xml 字符串 互转
转自: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 字符串 互转的更多相关文章
- org.w3c.dom.Document 与org.dom4j.Document互转
public static Document parse(org.w3c.dom.Document doc) throws Exception { if (doc == null) { return ...
- 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 ...
- [ java 工具类] xml字符串解析成Map(DOM解析)
package com.tencent.jungle.wechat.util; import com.google.inject.Singleton; import org.w3c.dom.Docum ...
- org.w3c.dom(java dom)解析XML文档
位于org.w3c.dom操作XML会比较简单,就是将XML看做是一颗树,DOM就是对这颗树的一个数据结构的描述,但对大型XML文件效果可能会不理想 首先来了解点Java DOM 的 API:1.解析 ...
- org.w3c.dom。 XML解析 练习
HTML文档 1 import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; ...
- 精讲 org.w3c.dom(java dom)解析XML文档
org.w3c.dom(java dom)解析XML文档 位于org.w3c.dom操作XML会比较简单,就是将XML看做是一颗树,DOM就是对这颗树的一个数据结构的描述,但对大型XML文件效果可能会 ...
- java解析xml字符串方法
一,用DOM4J 针对无重复标签的xml字符串格式,如下: 针对此种情况可用DOM4J解析法,引入 dom4j的相关jar包代码如下: Document document=DocumentHelpe ...
- xml转Map,对象,Map转xml,inputs tram 转xml 字符串的工具类方法
众所周知,大家在微信开发工程中,由于微信开发文档中,对于消息的接收发送都是基础xml数据的(太坑了),所以我们需要对XML进行解析转换: 1.我们先引入所需要的依赖 dom4j (解析xml的),xs ...
- javaxml文件基础:Dom怎么生成xml文件
package CreateXmlByDom; import java.io.File; import javax.xml.parsers.DocumentBuilder; import javax. ...
随机推荐
- vue使用formData进行文件上传
本文为博主原创,未经允许不得转载 1.vue页面 <ux-form ref="formRef" layout="vertical"> <ux- ...
- 如何开发一个npm包并发布到npm中央仓库
转自: https://liaolongdong.com/2019/01/24/publish-public-npm.html 如何开发一个npm包并发布到npm中央仓库需求背景:平时在项目工作中可能 ...
- Spark资源调度及任务调度
1. 资源分配 通过SparkSubmit进行提交应用后,首先会创建Client将应用程序(字节码文件.class)包装成Driver,并将其注册到Master.Master收到Client的注册请 ...
- (转载)Universal Correspondence Network
转载自:Chris Choy's blog Universal Correspondence Network In this post, we will give a very high-level ...
- [LeetCode] 305. Number of Islands II 岛屿的数量 II
A 2d grid map of m rows and n columns is initially filled with water. We may perform an addLand oper ...
- [LeetCode] 583. Delete Operation for Two Strings 两个字符串的删除操作
Given two words word1 and word2, find the minimum number of steps required to make word1 and word2 t ...
- GitLab - 一些基础使用
1 - GitLab角色权限 1.1 组(同一组成员的行为权限) 管理员创建不同的分组,然后设定分组的负责人(Owner) Owner可以添加组员,为组创建项目,指定项目的负责人 项目负责人可以添加项 ...
- Tomcat一些说明
嗯,昨天将有关JDK的知识稍微整理了一下,现在稍微整理一下有关Tomcat的! 1:Tomcat是什么? Tomcat是当今世界上使用最为广泛的.开源免费的Servlet/JSP容器,其主要功能是用于 ...
- swool教程链接汇总
参考地址: swoole教程第一节:进程管理模块(Process)-上 swoole教程第二节:基础的通讯实现-server篇-1 W3Cschool的swoole的系统教程 csdn网站swoole ...
- swoole实战1-初识swoole
原文地址:https://www.jianshu.com/p/008d5702d01f 安装swoole 以mac操作系统为例,如果你是mac新手,推荐阅读 程序员如何优雅使用mac 环境要求:php ...