xml和字符串转换

// 字符串转XML 

Java代码 
1.String xmlStr = \"......\";   
2.StringReader sr = new StringReader(xmlStr);   
3.InputSource is = new InputSource(sr);   
4.DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();   
5.DocumentBuilder builder=factory.newDocumentBuilder();   
6.Document doc = builder.parse(is);  
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转字符串 

Java代码 
1.TransformerFactory  tf  =  TransformerFactory.newInstance();   
2.Transformer t = tf.newTransformer();   
3.t.setOutputProperty(\"encoding\",\"GB23121\");//解决中文问题,试过用GBK不行   
4.ByteArrayOutputStream  bos  =  new  ByteArrayOutputStream();   
5.t.transform(new DOMSource(doc), new StreamResult(bos));   
6.String xmlStr = bos.toString();  
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)