Hussey123
Hussey123

Reputation: 479

Split XML using a Xpath Java

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?

Upvotes: 1

Views: 1700

Answers (1)

newuserua_ext
newuserua_ext

Reputation: 512

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

Upvotes: 1

Related Questions