1

I have following XML string.

<Engineers>
    <Engineer>
        <Name>JOHN</Name>
        <Position>STL</Position>
        <Team>SS</Team>
    </Engineer>
    <Engineer>
        <Name>UDAY</Name>
        <Position>TL</Position>
        <Team>SG</Team>
    </Engineer>
    <Engineer>
        <Name>INDRA</Name>
        <Position>Director</Position>
        <Team>PP</Team>
    </Engineer>
</Engineers>

I need to split this xml into smaller xml strings when Xpath is given as Engineers/Enginner.

Smaller xml strings are as follows

<Engineers>
    <Engineer>
        <Name>INDRA</Name>
        <Position>Director</Position>
        <Team>PP</Team>
    </Engineer>
</Engineers>

<Engineers>
    <Engineer>
        <Name>JOHN</Name>
        <Position>STL</Position>
        <Team>SS</Team>
    </Engineer>
</Engineers>

How can I do this using Java document builder and XpathFactory?

1

1 Answer 1

1

This will be help you;

Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File("../Xpath/src/example.xml"));
        XPath xPath = XPathFactory.newInstance().newXPath();
        XPathExpression exp = xPath.compile("//Engineer");
        NodeList nl = (NodeList)exp.evaluate(doc, XPathConstants.NODESET);
        System.out.println("Found " + nl.getLength() + " results");

        for (int i = 0; i < nl.getLength(); i++) {
            Node node = nl.item(i);
             StringWriter buf = new StringWriter();
                Transformer xform = TransformerFactory.newInstance().newTransformer();
                xform.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
                xform.transform(new DOMSource(node), new StreamResult(buf));
                System.out.println(buf.toString());
        }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.