Tuesday, June 26, 2012

Multiple Expression Execution on XPath

How to specify Multiple XPath Expression at a time


Sometimes we need to specify multiple XPath expressions to evaluate XML file.

For instance let's consider the following XML File.

<FieldCollection>
  <VarificationField>
    <CreditCardNumber>378291726006009</CreditCardNumber>
    <CreditCardCVV>1234</CreditCardCVV>
    <fieldName>CreditCard</fieldName>
  </VarificationField>
</FieldCollection>

Say we need to select two different nodes say CreditCardNumber and CreditCardCVV out of a xml file and mask them.

We can use "|" separator for specifying more then one path, like as follows.

//*/CreditCardNumber/text() | //*/CreditCardCVV/text()

As shown above we piped two different XPath to build a single XPathExpression which would be used to evaluate the XML documents.

String path = "//*/CreditCardNumber/text() | //*/CreditCardCVV/text() ";
XPathFactory factory = XPathFactory.newInstance();
XPath xPath = factory.newXPath();
XPathExpression  xPathExpression = xPath.compile(path);
Document doc = parseXmlStringFromFile(xmlDocument);
Object result = xPathExpression.evaluate(doc, XPathConstants.NODESET);

After executing the above lines of code, we are running expression which contains two XPath against the document and would return two respective nodeset(One for CreditcardNumber and the other for CreditCardCVV).


No comments :

Post a Comment