Posts

Showing posts with the label Xpath

Multiple Expression Execution on XPath

How to specify Multiple XPath Expression at a time Sometimes we need to specify  multiple  XPath  e xpressions 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...

JDOM Parser to Read and Update XML

JDom is a java based library for processing XML.  It is light weight and fast. It is simple to use since it was designed for Java. JDom Documents can be used with DOM tree or SAX events. JDom Support XPath. The following examples shows some common usecases with JDom such as 1) Update the value of a node in the xml 2) Print the xml from JDom Document 3) Get a particular Node using XPath //Update the value of a node Document doc = new SAXBuilder().build(new File(fileToProcess)); Element rootElement = doc.getRootElement(); Element book = rootElement.getChild("book").getChild("author") .setText("Sidd"); //Print the xml XMLOutputter outputter = new XMLOutputter(); outputter.output(doc, System.out); // Get a particular Node useing XPath XPath xPath = XPath.newInstance("/bookstore/book[bookid=$bookid]/bookid"); xPath.setVariable("bookid", "id1002"); Element guest = (Element) xPath.selectSingleNode(doc); System.out.pri...