2011-06-30 10 views
12

używam tego kodu do analizowania XMLjava - Geting całą zawartość węzła XML jako ciąg

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

Teraz chcę uzyskać wszystkie treści z węzła xml. Jak z tego xml

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

Więc jeśli chcesz uzyskać wszystkie treści <human> jako tekst.

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

Jak mogę ją dostać?

Odpowiedz

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

Wygląda podobnie do tego fragmentu: http://snippets.dzone.com/posts/show/4011 –

+0

Dzięki. To działa. – Barun

Powiązane problemy