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?

WitVault
  • 23,445
  • 19
  • 103
  • 133
Hussey123
  • 479
  • 1
  • 5
  • 21
  • You can refer to this question: http://stackoverflow.com/questions/10734847/java-xpath-get-all-the-elements-that-match-a-query – KC Wong Oct 13 '16 at 06:19

1 Answers1

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());
        }
newuserua_ext
  • 577
  • 6
  • 18