一、使用最原始的Javax.XML.parsers,標准的jdk api
// 字符串轉XML
String XMLStr = \"......\";
StringReader sr = new StringReader(XMLStr);
InputSource is = new InputSource(sr);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder=factory.newDocumentBuilder();
Document doc = builder.parse(is);
//XML轉字符串
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t = tf.newTransformer();
t.setOutputProperty(\"encoding\",\"GB23121\");//解決中文問題,試過用GBK不行
ByteArrayOutputStream bos = new ByteArrayOutputStream();
t.transform(new DOMSource(doc), new StreamResult(bos));
String XMLStr = bos.toString();
這裡的XML DOCUMENT為org.w3c.dom.Document
二、使用dom4j後程序變得更簡單
// 字符串轉XML
String XMLStr = \"......\";
Document document = DocumentHelper.parseText(XMLStr);
// XML轉字符串
Document document = ...;
String text = document.asXML();
這裡的XML DOCUMENT為org.dom4j.Document
三、使用JDOM
JDOM的處理方式和第一種方法處理非常類似
//字符串轉XML
String XMLStr = \".....\";
StringReader sr = new StringReader(XMLStr);
InputSource is = new InputSource(sr);
Document doc = (new SAXBuilder()).build(is);
//XML轉字符串
Format format = Format.getPrettyFormat();
format.setEncoding(\"gb2312\");//設置XML文件的字符為gb2312,解決中文問題
XMLOutputter xmlout = new XMLOutputter(format);
ByteArrayOutputStream bo = new ByteArrayOutputStream();
XMLout.output(doc,bo);
String XMLStr = bo.toString();
這裡的XML DOCUMENT為org.jdom.Document
四、Javascript中的處理
//字符串轉XML
var XMLStr = \".....\";
var xmlDoc = new ActiveXObject(\"Microsoft.XMLDOM\");
XMLDoc.async=false;
xmlDoc.loadXML(XMLStr);
//可以處理這個XMLDoc了
var name = XMLDoc.selectSingleNode(\"/person/name\");
alert(name.text);
//XML轉字符串
var XMLDoc = ......;
var xmlStr = xmlDoc.XML
這裡的XML DOCUMENT為Javascript版的XMLDOM