2011-09-04 53 views
8

完整的XML文本我已阅读XML文件在Java中有这样的代码:得到节点实例

File file = new File("file.xml"); 
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
DocumentBuilder db = dbf.newDocumentBuilder(); 
Document doc = db.parse(file); 

NodeList nodeLst = doc.getElementsByTagName("record"); 

for (int i = 0; i < nodeLst.getLength(); i++) { 
    Node node = nodeLst.item(i); 
... 
} 

所以,我怎样才能从节点实例完整的XML内容? (包括所有标签,属性等)

谢谢。

+1

你是什么意思 “得到充分的XML内容” 呢?你期待什么类型的对象回来?一个字符串?还有别的吗? –

+0

完整的xml内容将在file.xml中,或者我缺少重点?否则请尝试http://stackoverflow.com/questions/35785/xml-serialization-in-java或http://xstream.codehaus.org/tutorial.html。 –

+0

@PaulGrime,你的意思是,我必须用XML序列化器来序列化“节点”实例吗? – xVir

回答

13

查看此其他answer来自stackoverflow。

您将使用DOMSource(而不是StreamSource),并在构造函数中传递您的节点。

然后,您可以将节点转换为字符串。

快速样品:

public class NodeToString { 
    public static void main(String[] args) throws TransformerException, ParserConfigurationException, SAXException, IOException { 
     // just to get access to a Node 
     String fakeXml = "<!-- Document comment -->\n <aaa>\n\n<bbb/> \n<ccc/></aaa>"; 
     DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); 
     Document doc = docBuilder.parse(new InputSource(new StringReader(fakeXml))); 
     Node node = doc.getDocumentElement(); 

     // test the method 
     System.out.println(node2String(node)); 
    } 

    static String node2String(Node node) throws TransformerFactoryConfigurationError, TransformerException { 
     // you may prefer to use single instances of Transformer, and 
     // StringWriter rather than create each time. That would be up to your 
     // judgement and whether your app is single threaded etc 
     StreamResult xmlOutput = new StreamResult(new StringWriter()); 
     Transformer transformer = TransformerFactory.newInstance().newTransformer(); 
     transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); 
     transformer.transform(new DOMSource(node), xmlOutput); 
     return xmlOutput.getWriter().toString(); 
    } 
} 
+1

它工作正常!谢谢! – xVir

+4

什么是可怕的Api! – jeremyjjbrown