Wednesday, June 20, 2012

JAVA XPATH Examples for C# developers

In C#, you can use XLinq OR XPath, to query the document quickly. and for the xpath, just load one document, then pass the xpath expression to invoke the methods, you get the results.
here is one basic document,

<?xml version="1.0" encoding="UTF-8"?>
        <item id="1">
            <productname>Intel CPU I7</productname>
        <item id="2">
            <productname>Windows 8</productname>

If we need to get the sum of all items, we can use the xpath as sum(//item/amount)
in C#, here is the code, let’s assume the document are located in order.xml
using xlinq,
or using xpath,

both outputs 310 here,
if use java, code will be more complicated. here is one sample using the DOM and Xpath in java

  DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
       DocumentBuilder builder=factory.newDocumentBuilder();
       Document doc=builder.parse(domdemo.class.getResourceAsStream("/order.xml"));
       XPathFactory xfactory=XPathFactory.newInstance();
       XPath xpath=xfactory.newXPath();
       XPathExpression exp=xpath.compile("sum(//item/amount)");
       Object o=exp.evaluate(doc, XPathConstants.NUMBER);

that’s java, more codes to do the same thing compared with C#.

No comments:

Locations of visitors to this page