2011-09-04 15 views
8

से पूर्ण एक्सएमएल पाठ मैं एक्सएमएल फ़ाइल जावा में इस तरह के कोड के साथ पढ़ा है:हो जाओ नोड उदाहरण

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

तो, मैं नोड उदाहरण से पूर्ण एक्सएमएल सामग्री मिल सकता है? (सभी टैग सहित, गुण आदि)

धन्यवाद।

+1

क्या आप 'पूर्ण एक्सएमएल सामग्री प्राप्त "से क्या मतलब है? आप किस प्रकार की वस्तु वापस पाने की उम्मीद कर रहे हैं? एक स्ट्रिंग? कुछ और? –

+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

क्या एक भयानक एपीआई! – jeremyjjbrown

संबंधित मुद्दे