2011-09-04 6 views
8

He leído archivo XML en Java con dicho código:se llenan de texto XML de ejemplo 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); 
... 
} 

Entonces, ¿cómo puedo obtener el contenido completo de XML ejemplo nodo? (incluyendo todas las etiquetas, atributos, etc.)

Gracias.

+1

¿Qué quiere decir por "obtener el contenido XML completo"? ¿Qué tipo de objeto esperas recuperar? ¿Una cuerda? ¿Algo más? –

+0

El contenido xml completo estará en file.xml, ¿o me falta el punto? De lo contrario, pruebe http://stackoverflow.com/questions/35785/xml-serialization-in-java o http://xstream.codehaus.org/tutorial.html. –

+0

@PaulGrime, ¿te refieres a lo que debo serializar la instancia de "nodo" con el serializador XML? – xVir

Respuesta

13

Echa un vistazo a este otro answer de stackoverflow.

Utilizaría un DOMSource (en lugar de StreamSource) y pasaría su nodo en el constructor.

Luego puede transformar el nodo en una Cadena.

muestra rápida:

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

¡Está funcionando! ¡Gracias! – xVir

+4

¡Qué horrible Api! – jeremyjjbrown