转自: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. 检测是否安装或者开启flash

    function flashChecker() { var hasFlash = 0; //是否安装了flash var flashVersion = 0; //flash版本 if(document ...

  2. 自动化远程部署shell脚本

    历史原因,有一段时间,项目开发采用一种模式:项目开发及代码版本管理在外网,而主要测试在内网.所以为了同步开发进度,每天会将所有服务在外网jenkins上打包好,然后将服务jar包拷进内网,由于内网服务 ...

  3. git 只提交部分修改文件

    1.git status //查看修改文件状态 2.git add  //将想要提交的文件add到本地库 4.git status  //查看修改文件状态 3.git commit  //提交add到 ...

  4. 必须要注意的 C++ 动态内存资源管理(六)——vector的简单实现

    必须要注意的 C++ 动态内存资源管理(六)——vector的简单实现 十六.myVector分析         我们知道,vector类将其元素存放在连续的内存中.为了获得可接受的性能,vetor ...

  5. 关于将汉语拼音字母“ü”改成“v”的设想和建议

    http://bbs.tianya.cn/post-free-1667253-1.shtml?_t=t -- 徐州工业职业技术学院 孙生强 <汉语拼音方案>为中国人的语言文字学习带来极大方 ...

  6. mysql全文索引:fulltext

    fulltext全文索引 要使用全文索引,不仅需要把某个字段的索引类型设置为fulltext,还需要修改mysql配置文件: [mysqld] ft_wordlist_charset #表示词典的字符 ...

  7. Shell流程控制语句case

    case语法格式: case 变量或表达式 in 变量或表达式1) 命令1 ;; 变量或表达式2) 命令2 ;; ...... *) 默认命令 esac case语句流程控制图:  实例: [root ...

  8. lint-staged那些事儿

    一.工具选型 [预提交工具](https://www.npmtrends.com/lint-staged-vs-pre-commit-vs-pretty-quick) 1.lint-staged 检查 ...

  9. [LeetCode] 40. Combination Sum II 组合之和 II

    Given a collection of candidate numbers (candidates) and a target number (target), find all unique c ...

  10. [LeetCode] 186. Reverse Words in a String II 翻转字符串中的单词 II

    Given an input string, reverse the string word by word. A word is defined as a sequence of non-space ...