2011-09-04 13 views
8

Ho letto file XML in Java con tale codice:ottenere pieno testo XML da esempio Nodo

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

Così, come posso ottenere contenuto completo XML dal nodo esempio? (compresi tutti i tag, attributi, ecc.)

Grazie.

+1

Che cosa si intende per "ottenere contenuti XML completi"? Che tipo di oggetto ti aspetti di riavere? Una stringa? Qualcos'altro? –

+0

Il contenuto XML completo sarà in file.xml o mi manca il punto? Altrimenti prova http://stackoverflow.com/questions/35785/xml-serialization-in-java o http://xstream.codehaus.org/tutorial.html. –

+0

@PaulGrime, intendi, cosa devo serializzare l'istanza "nodo" con serializzatore XML? – xVir

risposta

13

Dai un'occhiata a questo altro answer da stackoverflow.

Si utilizzerà DOMSource (anziché StreamSource) e si passa il nodo nel costruttore.

Quindi è possibile trasformare il nodo in una stringa.

campione rapida:

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

Funziona! Grazie! – xVir

+4

Che terribile Api! – jeremyjjbrown

Problemi correlati