xml和字符串的转换

请注意,本文编写于 3669 天前,最后修改于 273 天前,其中某些信息可能已经过时。

// 字符串转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","utf-8");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
t.transform(new DOMSource(doc), new StreamResult(bos));
String xmlStr = bos.toString();

添加新评论