String字符串互相转换成XML格式

来源:互联网 发布:java stringbuffer 编辑:程序博客网 时间:2024/05/29 18:50

在NC接口的时候,需要把String字符串转换成XML格式,同时也需要把XML格式的文件转换成String字符串;

package com.accord.test;import java.io.ByteArrayInputStream;import java.io.File;import java.io.FileWriter;import java.io.IOException;import org.dom4j.Document;import org.dom4j.DocumentException;import org.dom4j.io.OutputFormat;import org.dom4j.io.SAXReader;import org.dom4j.io.XMLWriter;public class XmlUtil {public static void main(String[] args) throws Exception {XmlUtil xu = new XmlUtil();String xmlString = xu.xmlChangeString("E:\\3.xml");System.out.println(xmlString);}public String xmlChangeString(String fileName) {try {SAXReader saxReader = new SAXReader();// 新建一个解析类//Document tempDocument = saxReader.read(XmlUtil.class.getClassLoader().getResourceAsStream(fileName));// 读入一个文件Document tempDocument = saxReader.read(new File(fileName));return tempDocument.asXML();} catch (DocumentException e) {e.printStackTrace();}return null;}// 将字符串string类型转换成xml文件public void strChangeXML(String str) throws IOException {SAXReader saxReader = new SAXReader();Document document;try {document = saxReader.read(new ByteArrayInputStream(str.getBytes("UTF-8")));OutputFormat format = OutputFormat.createPrettyPrint();/** 将document中的内容写入文件中 */XMLWriter writer = new XMLWriter(new FileWriter(new File("E:\\11111.xml")),format);writer.write(document);writer.close();} catch (DocumentException e) {e.printStackTrace();}}}
需要dom4j.jar

原创粉丝点击