一,
使用JDOM
1.字符串轉Document對象
String xmlStr = "....."; StringReader sr = new StringReader(xmlStr); InputSource is = new InputSource(sr); Document doc = (new SAXBuilder()).build(is);
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();
二,
使用最原始的javax.xml.parsers,標准的jdk api
1.字符串轉Document對象
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);
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();
三,
使用dom4j(這是最簡單的方法)
1.字符串轉Document對象
String xmlStr = "......";
Document document = DocumentHelper.parseText(xmlStr);
Document document = ...;
String text = document.asXML();
四,在JavaScript中的處理
1.字符串轉Document對象
var xmlStr = "....."; var xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); xmlDoc.async=false; xmlDoc.loadXML(xmlStr); //可以處理這個xmlDoc了 var name = xmlDoc.selectSingleNode("/person/name"); alert(name.text);
var xmlDoc = ......;
var xmlStr = xmlDoc.xml