2011-09-04 32 views
8

Tôi đã đọc tập tin XML trong Java với mã ví dụ:Nhận đầy đủ xml văn bản từ Node dụ

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); 
... 
} 

Vì vậy, làm thế nào tôi có thể nhận được nội dung xml đầy đủ từ dụ nút? (bao gồm tất cả các thẻ, thuộc tính, v.v.)

Cảm ơn.

+1

Ý anh là gì bởi "có được nội dung xml đầy đủ"? Bạn muốn quay trở lại loại đối tượng nào? Một chuỗi? Thứ gì khác? –

+0

Nội dung xml đầy đủ sẽ nằm trong tệp tin.xml, hoặc tôi có bị thiếu điểm không? Nếu không, hãy thử http://stackoverflow.com/questions/35785/xml-serialization-in-java hoặc http://xstream.codehaus.org/tutorial.html. –

+0

@PaulGrime, ý bạn là gì, tôi phải serialize "nút" thể hiện với serializer XML? – xVir

Trả lời

13

Khám phá điều này khác answer từ stackoverflow.

Bạn sẽ sử dụng DOMSource (thay vì StreamSource) và chuyển nút của bạn trong hàm tạo.

Sau đó, bạn có thể chuyển đổi nút thành Chuỗi.

mẫu nhanh:

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

Nó hoạt động! Cảm ơn! – xVir

+4

Thật là một Api khủng khiếp! – jeremyjjbrown

Các vấn đề liên quan