Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get full xml text from Node instance

Tags:

java

xml

I have read XML file in Java with such code:

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);
...
}

So, how I can get full xml content from node instance? (including all tags, attributes etc.)

Thanks.

like image 756
xVir Avatar asked Sep 04 '11 14:09

xVir


People also ask

What is a XMLnode?

According to the XML DOM, everything in an XML document is a node: The entire document is a document node. Every XML element is an element node. The text in the XML elements are text nodes. Every attribute is an attribute node.

What is XML node value?

The nodeValue property is used to get the text value of a node. The getAttribute() method returns the value of an attribute.

What is parent node in XML?

The root node is the "parent" node that all nodes are children of. For example if you have an XML file where you are storing books, your root node would be <books> and your XML file would look something like this: <books> <book id="1"> <author id=""/>


1 Answers

Check out this other answer from stackoverflow.

You would use a DOMSource (instead of the StreamSource), and pass your node in the constructor.

Then you can transform the node into a String.

Quick sample:

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();
    }
}
like image 58
Paul Grime Avatar answered Sep 29 '22 13:09

Paul Grime