Java Document (xml)对象转String

(9条消息) Java Document对象转String_weixin_33860147的博客-CSDN博客

 Code1

package com.project.util;
 
import java.io.IOException;
import java.io.StringWriter;
 
import org.apache.log4j.Logger;
import org.w3c.dom.Document;
 
import com.sun.org.apache.xml.internal.serialize.OutputFormat;
import com.sun.org.apache.xml.internal.serialize.XMLSerializer;
 
public class DocumentUtil {
 
	public static Logger log = Logger.getLogger(DocumentUtil.class.getClass());
	
	/**
	 * Document 转换为 String 并且进行了格式化缩进
	 * 
	 * @param doc XML的Document对象
	 * @return String
	 */
	public static String doc2FormatString(Document doc) {	
		String docString = "";
		if(doc != null){
			StringWriter stringWriter = new StringWriter();
			try{
				OutputFormat format = new OutputFormat(doc,"UTF-8",true);
				//format.setIndenting(true);//设置是否缩进,默认为true
				//format.setIndent(4);//设置缩进字符数
				//format.setPreserveSpace(false);//设置是否保持原来的格式,默认为 false
				//format.setLineWidth(500);//设置行宽度
				XMLSerializer serializer = new XMLSerializer(stringWriter,format);
				serializer.asDOMSerializer();
				serializer.serialize(doc);
				docString = stringWriter.toString();
			}catch(Exception e){
				e.printStackTrace();
			}finally{
				if(stringWriter != null){
		        	try {
						stringWriter.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
	        	}
			}
		}
		log.error("XML内容:"+docString);
		return docString;
	}
	
}

 Code2:

/**
	 * org.w3c.dom.Document 转换为 String
	 * 
	 * @param org.w3c.dom.Document对象
	 * @return String
	 */
	public static String docToString(Document doc) {
		String docStr = "";
		if(doc!=null){
			try{
				TransformerFactory transformerFactory = TransformerFactory.newInstance();                
				Transformer transformer = transformerFactory.newTransformer();                
				transformer.setOutputProperty("encoding", "UTF-8");                
				ByteArrayOutputStream outputStream = new ByteArrayOutputStream();                
				transformer.transform(new DOMSource(doc), new StreamResult(outputStream));                
				//docStr = outputStream.toString();
				docStr = outputStream.toString("UTF-8");
				System.out.println("\n**********************     【org.w3c.dom.Document对象转XML字符串内容:】       **********************\n"+docStr);
			}catch(Exception e){
				e.printStackTrace();
			}
		}
		return docStr;
	}

String 转 Document

org.w3c.dom document 和xml 字符串 互转 - Sharpest - 博客园 (cnblogs.com)

/**
* 将传入的一个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());
}
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; public class ReadXML { public static void main(String[] args) { try { // 得到DOM解析器的工厂实例 DocumentBuilderFactory domfac = DocumentBuilderFactory.newInstance(); // 从DOM工厂获得DOM解析器 DocumentBuilder dombuilder = domfac.newDocumentBuilder(); // 把要解析的XML文档化为输入流,以便DOM解析器解析它 InputStream is = new FileInputStream("test.xml"); // 解析XML文档的输入流,得到一个Document Document doc = dombuilder.parse(is); // 得到XML文档的根节点 Element root = doc.getDocumentElement(); // 得到节点的子节点 NodeList books = root.getChildNodes(); if (books != null) { // 轮循子节点 for (int i = 0; i < books.getLength(); i++) { // 获取book节点 Node book = books.item(i); if (book.getNodeType() == Node.ELEMENT_NODE) { // 取得节点的属性值 String email = book.getAttributes().getNamedItem( "email").getNodeValue(); System.out.println(email); // 轮循子节点 for (Node node = book.getFirstChild(); node != null; node = node.getNextSibling()) { if (node.getNodeType() == Node.ELEMENT_NODE) { if (node.getNodeName().equals("name")) { // 获得节点的文本值 String name = node.getFirstChild() .getNodeValue(); System.out.println(name); } if (node.getNodeName().equals("price")) { // 获得节点的文本值 String price = node.getFirstChild() .getNodeValue(); System.out.println(price); } } } } } } } // 异常处理 catch (ParserConfigurationException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值