Class Path


  • public class Path
    extends Object

    Provides an object path navigation class to return the value for the given expression. This class will automatically select the appropriate path navigation library for the given source object which may be JSON text, XML text, XML document or Java POJO (Plain Old Java Object).

    Path Sources

    The supported Path sources can be constructed by JSON text, XML text, XML document or Java POJO.

    Expressions

    Here is a complete overview and a side by side comparison of the JSONPath syntax elements with its XPath counterparts.

    XPath JSONPath Description
    / $ the root object/element
    . @ the current object/element
    / . or [] child operator
    .. n/a parent operator
    // .. recursive descent. JSONPath borrows this syntax from E4X.
    * * wildcard. All objects/elements regardless their names.
    @ n/a attribute access. JSON structures don't have attributes.
    [] [] subscript operator. XPath uses it to iterate over element collections and for predicates. In Javascript and JSON it is the native array operator.
    | [,] Union operator in XPath results in a combination of node sets. JSONPath allows alternate names or array indices as a set.
    n/a [start:end:step] array slice operator borrowed from ES4.
    [] ?() applies a filter (script) expression.
    n/a () script expression, using the underlying script engine.
    () n/a grouping in Xpath

    JSON Sources

    With JSON sources the expression language used is JSONPath. When using the val(exp) method this class will return the text content value for the first selected node, or null if no node was found. The expression operators include $(root node of the structure), @ (current node that is being processed, e.g. "user[?(@.firstName==John)]") and * (wildcard indicating all elements in scope, e.g. user[*]). See JayWay JSONPath Library Guide for more documentation.

    Object Sources

    With Object sources the expression language used is "property names", e.g. "user.firstName". When using the val(exp) method this class will return the text content value for the first selected node, or null if no node was found.

    XML Sources

    Note that the implementation is namespace aware but ignores default namespace's override.

    Examples

    JSON Examples

    This Groovy example creates Path from JSON string, and then reads out a value from path.

     import com.avoka.tm.util.Path
    
     String json =
     '''{
        "address": {
          "line1": "1 Street",
          "postCode": 2000
        }
     }'''
    
     Path path = new Path(json)
    
     def line1 = path.val('address.line1')
     def postCode = path.val('$.[\'address\'].[\'postCode\']') 
    Note you have the full power of JSON Path so you can perform like:
     def addressNodeFiltered = path.val("address[?(@.postCode == 2000)]")
     def allAddressChildrenValuesList = path.val("address[*]") 

    Java Object Examples

    This Groovy example creates Path from Object, and then reads out a value from path.

     import com.avoka.tm.util.Path
    
     User user = new User()
     user.setFirstName("George")
    
     ContactDetails cd = new ContactDetails()
     cd.setEmail("[email protected]")
     user.setContactDetails(cd)
    
     Address address = new Address()
     address.setCity("Sydney")
     address.setPostCode(2153)
     user.getAddressList().add(address)
    
     Path path = new Path(user)
    
     def userFirstName = path.val("firstName")
     def userEmail = path.val("contactDetails.email")
     def postCode = path.val("addressList[0].postCode") 

    XML Examples

    This Groovy example creates Path from XML string, and then reads out a value from path.

     import com.avoka.tm.util.Path
    
     //  source - XML text
     String formXml =
     '''<AvokaSmartForm>
        <YourDetails>
           <FirstName> ... </FirstName>
           <LastName> ... </LastName>
           <Email> ... </Email>
        </YourDetails>
     </AvokaSmartForm>'''
    
     Path path = new Path(formXml)
     def userFirstName = path.val("//FirstName")
     def userEmail = path.val("/AvokaSmartForm/YourDetails/Email")
    
     // schemaSeed - XML Document source
     Path path2 = new Path(schemaSeed)
     def userEmail = path2.val("//Email") 
    Note you have the full power of XQuery so you can perform XQuerys like:
     def countryList = path.val("//root/country[@value='USA']") 

    The Path class also provides a nodes() method which will return a typed List of XML Nodes which can be iterated over. In contrast the Path val() method will return the text content of the first selected XML Node.

     import com.avoka.tm.util.Path
     import org.w3c.dom.Node
    
     def xml =
     '''<bar>
         <drink type="Beer"> 4 Pines </drink>
         <drink type="Beer"> Coopers </drink>
         <drink type="Wine"> Cab Sav </drink>
     </bar>'''
    
     // Select first value
     Path path = new Path(xml)
    
     def firstDrink = path.val('//drink')
    
     println 'firstDrink value: ' + firstDrink + ', type: ' + firstDrink.class.simpleName
    
     // Select node list
     List<Node> drinks = path.nodes('//drink')
    
     for (drink in drinks) {
         println 'textContent: ' + drink.textContent + ', type: ' + drink.class.simpleName + ', toString: ' + drink
     } 

    Script output results:

     firstDrink value: 4 Pines, type: String
    
     textContent: 4 Pines, type: DeferredElementImpl, toString: <?xml version="1.0" encoding="UTF-8"?> <drink type="Beer">4 Pines</drink>
     textContent: Coopers, type: DeferredElementImpl, toString: <?xml version="1.0" encoding="UTF-8"?> <drink type="Beer">Coopers</drink>
     textContent: Cab Sav, type: DeferredElementImpl, toString: <?xml version="1.0" encoding="UTF-8"?> <drink type="Wine">Cab Sav</drink> 
    Since:
    5.0.0
    • Constructor Detail

      • Path

        public Path​(Object source)
        Create a path evaluation object with the given source.
        Parameters:
        source - the source
    • Method Detail

      • val

        public Object val​(String path)

        Return the value for the given expression.

        With XML sources the expression language used is XPath. When using the val(exp) method this class will return the text content value for the first selected node, or null if no node was found.

        Parameters:
        path - the path expression to evaluate (required)
        Returns:
        value for the path expression, otherwise null if path is invalid or can not be found.
      • vals

        public List<Object> vals​(String path)

        Return the list of values for the given expression.

        With an XML source the expression language used is XPath. When using the vals(exp) method this class will return the text content value for the list of selected nodes, or an empty list if not found.

        Parameters:
        path - the path expression to evaluate (required)
        Returns:
        the list of values for the given expression, otherwise empty List if can not be found.
      • nodes

        public List<Node> nodes​(String path)

        Return the list of XML Node values for the given expression.

        This method will throw an UnsupportedOperationException if the Path source is not an XML source.

        Parameters:
        path - the path expression to evaluate (required)
        Returns:
        the list of DOM Node values for the given the path expression
      • paths

        public List<Path> paths​(String path)

        Return the list of paths for the given expression.

        Parameters:
        path - the path expression to evaluate (required)
        Returns:
        the list of values for the given expression.
      • firstPath

        public Path firstPath​(String path)

        Return the first path object for the given expression, or null if not resolved.

        Parameters:
        path - the path expression to evaluate (required)
        Returns:
        the first path object for the given expression, or null if not resolved.
        Since:
        18.11.0