开发者

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

开发者 https://www.devze.com 2023-02-07 03:54 出处:网络
I am looking for something like this : <Node1> <Child2 attr1=\"abc\"> <Child3 attr2=\"xyz\">

I am looking for something like this :

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

From 开发者_Python百科Node1 , I want to get the contents inside the node as text. The output I want is

"<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());
    }
}

See this question with other possible answers.

0

精彩评论

暂无评论...
验证码 换一张
取 消