簡體   English   中英

如何在Java中以字符串形式獲取XML節點內的內容

[英]How do I get contents inside an XML Node as String in Java

我正在尋找這樣的東西:

<Node1>
   <Child2 attr1="abc">
   <Child3 attr2="xyz">
<Node1>

從Node1,我想以文本形式獲取節點內的內容。 我想要的輸出是

"<Child2 attr1="abc"><Child3 attr2="xyz">"
   //Parse the input document
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(new File("yourfile.xml"));

        //Set up the transformer to write the output string
        TransformerFactory tFactory = TransformerFactory.newInstance();
        Transformer transformer = tFactory.newTransformer();
        transformer.setOutputProperty("indent", "yes");
        StringWriter sw = new StringWriter();
        StreamResult result = new StreamResult(sw);

        //Find the first child node 
        NodeList nl = doc.getDocumentElement().getChildNodes();
        DOMSource source = null;
        for(int x = 0;x < nl.getLength();x++)
        {
            Node e = nl.item(x);
            if(e instanceof Element)
            {
                source = new DOMSource(e);
                break;
            }
        }

        transformer.transform(source, result);
        System.out.println(sw.toString());
    }
}

請參閱此問題以及其他可能的答案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM