2011-06-30 10 views
12

Sto usando questo codice per il parsing XMLjava - Ottenendo tutti i contenuti di un nodo XML come stringa

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
    DocumentBuilder db = dbf.newDocumentBuilder(); 
    InputSource is = new InputSource(); 
    is.setCharacterStream(new StringReader(data)); 
    Document doc = db.parse(is); 

Ora voglio ottenere tutti i contenuti da un nodo XML. Come da questa xml

<?xml version='1.0'?> 
<type> 
    <human>      
    <Name>John Smith</Name>    
    <Address>1/3A South Garden</Address>  
    </human> 
</type> 

Quindi, se vuole ottenere tutti i contenuti di <human> come testo.

<Name>John Smith</Name> 
<Address>1/3A South Garden</Address> 

Come posso ottenerlo?

risposta

29
private String nodeToString(Node node) { 
    StringWriter sw = new StringWriter(); 
    try { 
    Transformer t = TransformerFactory.newInstance().newTransformer(); 
    t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); 
    t.transform(new DOMSource(node), new StreamResult(sw)); 
    } catch (TransformerException te) { 
    System.out.println("nodeToString Transformer Exception"); 
    } 
    return sw.toString(); 
} 
+0

Sembra simile a questo snippet: http://snippets.dzone.com/posts/show/4011 –

+0

Grazie. Sta funzionando. – Barun

Problemi correlati