Gopal
Gopal

Reputation: 91

xpath not accepting this expression

hello everyone i have on question for xpath

/abcd/nsanity/component_details[@component="ucs"]/command_details[<*configScope inHierarchical="true" cookie="{COOKIE}" dn="org-root" */>]/collected_data

i want to retrieve the string for above the xpath statement but when i am giving this xpath to xpath expression for evaulate it is throwing an exception like

Caused by: javax.xml.transform.TransformerException: A location path was expected, but the following token was encountered: <configScope

Upvotes: 0

Views: 5404

Answers (1)

vanje
vanje

Reputation: 10383

The bold part in your XPath expression is not a valid predicate expression. I can only guess, what do you want to achieve. If you want only the <command_details/> elements, which have a <configScope/> child element with attributes set to inHierarchical="true", cookie="{COOKIE}" and dn="org-root" then the XPath expression should be:

/abcd/nsanity/component_details[@component='ucs']/command_details[configScope[@inHierarchical='true' and @cookie='{COOKIE}' and @dn='org-root']]/collected_data

Here is an example XML:

<abcd>
  <nsanity>
    <component_details component="ucs">
      <command_details>
        <configScope inHierarchical="true" cookie="{COOKIE}" dn="org-root" />
        <collected_data>Yes</collected_data>
      </command_details>
      <command_details>
        <configScope inHierarchical="true" cookie="{COOKIE}" dn="XXX"/>
        <collected_data>No</collected_data>
      </command_details>
    </component_details>
  </nsanity>
</abcd>

The following Java program reads the XML file test.xml and evaluates the XPath expression (and prints the text node of element <collected_data/>.

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;


public class Test {

  public static void main(String[] args) throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    Document document = dbf.newDocumentBuilder().parse("test.xml");

    XPath xpath = XPathFactory.newInstance().newXPath() ;

    NodeList nl = (NodeList) xpath.evaluate("/abcd/nsanity/component_details[@component='ucs']/command_details[configScope[@inHierarchical='true' and @cookie='{COOKIE}' and @dn='org-root']]/collected_data", document, XPathConstants.NODESET);
    for(int i = 0; i < nl.getLength(); i++) {
      Element el = (Element) nl.item(i);
      System.out.println(el.getTextContent());
    }
  }
}

Upvotes: 2

Related Questions