2011-09-04 61 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