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"?>
<orders>
    <header>
        <date>2010-12-1</date>
    </header>
    <items>
        <item id="1">
            <productname>Intel CPU I7</productname>
            <amount>200</amount>
        </item> 
        <item id="2">
            <productname>Windows 8</productname>
            <amount>110</amount>
        </item>
    </items>
</orders>


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,
image
or using xpath,
image

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"));
      
       //item/productname
       XPathFactory xfactory=XPathFactory.newInstance();
       XPath xpath=xfactory.newXPath();
       XPathExpression exp=xpath.compile("sum(//item/amount)");
      
       Object o=exp.evaluate(doc, XPathConstants.NUMBER);
       System.out.println(o.toString());


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

No comments:

 
Locations of visitors to this page