生活随笔
收集整理的這篇文章主要介紹了
DOM方式进行的XML文件、Document、String之间的相互转换
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
http://kingxss.iteye.com/blog/1026954
XML文件test.xml:
Xml代碼
<?xml?
version=
"1.0"?
encoding=
"UTF-8"?><books><book><name>哈里波特
</name><price>10
</price><memo>這是一本很好看的書。
</memo></book></books>??
<?xml version="1.0" encoding="UTF-8"?><books><book><name>哈里波特</name><price>10</price><memo>這是一本很好看的書。</memo></book></books>
?
java代碼:
Java代碼
import?java.io.*; ??
import?java.net.URI; ????import?javax.xml.parsers.*; ??import?javax.xml.transform.*; ??import?javax.xml.transform.dom.DOMSource; ??import?javax.xml.transform.stream.StreamResult; ????import?org.w3c.dom.Document; ??import?org.xml.sax.InputSource; ????import?com.sun.org.apache.xml.internal.serialize.*; ???????????public?class?OperateXMLByDOM?{ ??????????????????public?static?Document?xml2Doc(String?filePath)?{ ??????????DocumentBuilderFactory?factory?=?DocumentBuilderFactory.newInstance(); ??????????DocumentBuilder?builder?=?null; ??????????FileInputStream?inputStream?=?null; ??????????Document?doc?=?null; ??????????try?{ ??????????????builder?=?factory.newDocumentBuilder(); ??????????????????????????????File?file?=?new?File(filePath); ??????????????doc?=?builder.parse(file); ??????????????????????????????URI?uri?=?new?URI(filePath);??????????????doc?=?builder.parse(uri.toString()); ??????????????????????????????inputStream?=?new?FileInputStream(filePath); ??????????????doc?=?builder.parse(inputStream); ??????????????return?doc; ??????????}?catch?(Exception?e)?{ ??????????????return?null; ??????????}?finally?{ ??????????????if?(inputStream?!=?null)?{ ??????????????????try?{ ??????????????????????inputStream.close(); ??????????????????}?catch?(IOException?e)?{ ??????????????????????return?null; ??????????????????} ??????????????} ??????????} ??????} ???????????????????public?static?String?doc2FormatString(Document?doc)?{??????? ??????????StringWriter?stringWriter?=?null; ??????????try?{ ??????????????stringWriter?=?new?StringWriter(); ??????????????if(doc?!=?null){ ??????????????????OutputFormat?format?=?new?OutputFormat(doc,"UTF-8",true); ??????????????????????????????????????????????????????????????????????????????????????????XMLSerializer?serializer?=?new?XMLSerializer(stringWriter,format); ??????????????????serializer.asDOMSerializer(); ??????????????????serializer.serialize(doc); ??????????????????return?stringWriter.toString(); ??????????????}?else?{ ??????????????????return?null; ??????????????} ??????????}?catch?(Exception?e)?{ ??????????????return?null; ??????????}?finally?{ ??????????????if(stringWriter?!=?null){ ??????????????????try?{ ??????????????????????stringWriter.close(); ??????????????????}?catch?(IOException?e)?{ ??????????????????????return?null; ??????????????????} ??????????????} ??????????} ??????} ?????? ?????????????????public?static?String?doc2String(Document?doc){ ??????????try?{ ??????????????Source?source?=?new?DOMSource(doc); ??????????????StringWriter?stringWriter?=?new?StringWriter(); ??????????????Result?result?=?new?StreamResult(stringWriter); ??????????????TransformerFactory?factory?=?TransformerFactory.newInstance(); ??????????????Transformer?transformer?=?factory.newTransformer(); ??????????????transformer.setOutputProperty(OutputKeys.INDENT,?"yes"); ??????????????transformer.transform(source,?result); ??????????????return?stringWriter.getBuffer().toString(); ??????????}?catch?(Exception?e)?{ ??????????????return?null; ??????????} ??????} ???????????????????public?static?Document?string2Doc(String?xml)?{ ??????????DocumentBuilderFactory?factory?=?DocumentBuilderFactory.newInstance(); ??????????DocumentBuilder?builder?=?null; ??????????Document?doc?=?null; ??????????InputSource?source?=?null; ??????????StringReader?reader?=?null; ??????????try?{ ??????????????builder?=?factory.newDocumentBuilder(); ??????????????reader?=?new?StringReader(xml); ??????????????source?=?new?InputSource(reader);??????????????doc?=?builder.parse(source); ??????????????return?doc; ??????????}?catch?(Exception?e)?{ ??????????????return?null; ??????????}?finally?{ ??????????????if(reader?!=?null){ ??????????????????reader.close(); ??????????????} ??????????} ??????} ???????????????????public?static?void?doc2XML(Document?doc,?String?path)?{ ??????????try?{ ??????????????Source?source?=?new?DOMSource(doc); ??????????????Result?result?=?new?StreamResult(new?File(path)); ??????????????Transformer?transformer?=?TransformerFactory.newInstance().newTransformer(); ??????????????transformer.setOutputProperty(OutputKeys.INDENT,?"yes"); ??????????????transformer.transform(source,?result); ??????????}?catch?(Exception?e)?{ ??????????????return; ??????????} ??????} ????????public?static?void?main(String[]?args)?{ ??????????Document?doc?=?xml2Doc("test.xml"); ??????????System.out.println(doc); ??????????System.out.println(doc2String(doc)); ??????????System.out.println(doc2FormatString(doc)); ??????????doc?=?string2Doc(doc2FormatString(doc)); ??????????doc2XML(doc,?"1.xml"); ??????} ??}??
import java.io.*;
import java.net.URI;import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;import org.w3c.dom.Document;
import org.xml.sax.InputSource;import com.sun.org.apache.xml.internal.serialize.*;/*** DOM方式操作XML* * @author Watson Xu* @date 2011-5-3 上午09:49:27*/
public class OperateXMLByDOM {/*** 將給定文件的內容或者給定 URI 的內容解析為一個 XML 文檔,并且返回一個新的 DOM Document 對象* * @param filePath 文件所在路徑* @return DOM的Document對象* @throws Exception*/public static Document xml2Doc(String filePath) {DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();DocumentBuilder builder = null;FileInputStream inputStream = null;Document doc = null;try {builder = factory.newDocumentBuilder();/* 通過文件方式讀取,注意文件保存的編碼和文件的聲明編碼要一致(默認文件聲明是UTF-8) */File file = new File(filePath);doc = builder.parse(file);/* 通過一個URL方式讀取 */URI uri = new URI(filePath);//filePath="http://java.sun.com/index.html"doc = builder.parse(uri.toString());/* 通過java IO 流的讀取 */inputStream = new FileInputStream(filePath);doc = builder.parse(inputStream);return doc;} catch (Exception e) {return null;} finally {if (inputStream != null) {try {inputStream.close();} catch (IOException e) {return null;}}}}/*** Document 轉換為 String 并且進行了格式化縮進* * @param doc XML的Document對象* @return String*/public static String doc2FormatString(Document doc) { StringWriter stringWriter = null;try {stringWriter = new StringWriter();if(doc != null){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);return stringWriter.toString();} else {return null;}} catch (Exception e) {return null;} finally {if(stringWriter != null){try {stringWriter.close();} catch (IOException e) {return null;}}}}/*** Document 轉換為 String* * @param doc XML的Document對象* @return String*/public static String doc2String(Document doc){try {Source source = new DOMSource(doc);StringWriter stringWriter = new StringWriter();Result result = new StreamResult(stringWriter);TransformerFactory factory = TransformerFactory.newInstance();Transformer transformer = factory.newTransformer();transformer.setOutputProperty(OutputKeys.INDENT, "yes");transformer.transform(source, result);return stringWriter.getBuffer().toString();} catch (Exception e) {return null;}}/*** String 轉換為 Document 對象* * @param xml 字符串* @return Document 對象*/public static Document string2Doc(String xml) {DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();DocumentBuilder builder = null;Document doc = null;InputSource source = null;StringReader reader = null;try {builder = factory.newDocumentBuilder();reader = new StringReader(xml);source = new InputSource(reader);//使用字符流創建新的輸入源doc = builder.parse(source);return doc;} catch (Exception e) {return null;} finally {if(reader != null){reader.close();}}}/*** Document 保存為 XML 文件* * @param doc Document對象* @param path 文件路徑*/public static void doc2XML(Document doc, String path) {try {Source source = new DOMSource(doc);Result result = new StreamResult(new File(path));Transformer transformer = TransformerFactory.newInstance().newTransformer();transformer.setOutputProperty(OutputKeys.INDENT, "yes");transformer.transform(source, result);} catch (Exception e) {return;}}public static void main(String[] args) {Document doc = xml2Doc("test.xml");System.out.println(doc);System.out.println(doc2String(doc));System.out.println(doc2FormatString(doc));doc = string2Doc(doc2FormatString(doc));doc2XML(doc, "1.xml");}
}
?
?
輸出的XML文件1.xml:
Xml代碼
<?xml?version="1.0"?encoding="UTF-8"?standalone="no"?>??<books>??????<book>??????????<name>哈里波特</name>??????????<price>10</price>??????????<memo>這是一本很好看的書。</memo>??????</book>??</books>??
?
總結
以上是生活随笔為你收集整理的DOM方式进行的XML文件、Document、String之间的相互转换的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。