当前位置: 技术问答>java相关
如何将xml文件的内容写在一个String里,在接析???????????急
来源: 互联网 发布时间:2015-10-14
本文导语: 如何将xml文件的内容写在一个String里,在接析???????????急 | InputStream in = new StringBufferInputStream( inString ); javax.xml.parsers.DocumentBuilder db = _documentBuilderFactory.newDocumentBuilder(); o...
如何将xml文件的内容写在一个String里,在接析???????????急
|
InputStream in = new StringBufferInputStream( inString );
javax.xml.parsers.DocumentBuilder db = _documentBuilderFactory.newDocumentBuilder();
org.w3c.dom.Document document = db.parse( in );
javax.xml.parsers.DocumentBuilder db = _documentBuilderFactory.newDocumentBuilder();
org.w3c.dom.Document document = db.parse( in );
|
楼上的回答反了吧。
我自己的static方法,如何得到Document就看楼主的了。我使用的是apache的xerces
import org.apache.xml.serialize.*;
import org.w3c.dom.*;
import org.apache.xerces.dom.*;
import java.io.*;
import java.util.*;
//放在什么地方自己看着办
public static String documentToString(org.w3c.dom.Document xmldoc){
try{
java.io.StringWriter o = new StringWriter();
OutputFormat of = new OutputFormat();
XMLSerializer serializer = new XMLSerializer(o,of);
serializer.asDOMSerializer();
serializer.serialize( xmldoc.getDocumentElement() );
return o.toString();
}
catch(IOException ioe){
ioe.printStackTrace();
return null;
}
}
我自己的static方法,如何得到Document就看楼主的了。我使用的是apache的xerces
import org.apache.xml.serialize.*;
import org.w3c.dom.*;
import org.apache.xerces.dom.*;
import java.io.*;
import java.util.*;
//放在什么地方自己看着办
public static String documentToString(org.w3c.dom.Document xmldoc){
try{
java.io.StringWriter o = new StringWriter();
OutputFormat of = new OutputFormat();
XMLSerializer serializer = new XMLSerializer(o,of);
serializer.asDOMSerializer();
serializer.serialize( xmldoc.getDocumentElement() );
return o.toString();
}
catch(IOException ioe){
ioe.printStackTrace();
return null;
}
}
|
java.io.PrintWriter out = response.getWriter();
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.ENCODING,"gb2312");
StreamResult result = new StreamResult(out);
transformer.transform(new DOMSource(document),result);
String tmp = out.toString();
这就是string了。
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.ENCODING,"gb2312");
StreamResult result = new StreamResult(out);
transformer.transform(new DOMSource(document),result);
String tmp = out.toString();
这就是string了。