Dom4j xpath problem

Hello all
I have several methods in which I noticed strange behavior
Here is the example:
I create xpath as object because of performance, cause i use it on thousands of files
XPath pathSpanPodzakonska = DocumentHelper.createXPath("//span[@class='palnk']");
I found h4 element via xpath with relative path to h4 element...
That works fine so far and founds h4 element that I need to.
final Element elementH4= (Element) document.selectSingleNode("//h4[@id='someId']");
Now i need to found some element inside that h4 tag
but what I get is first element in document, outside h4 element !!!
final Node nodeSpanPodzakonska = pathSpanPodzakonska.selectSingleNode(elementH4);
That works same even if i write
final Node nodeSpanPodzakonska = elementH4.selectSingleNode("//span[@class='palnk']");
If I write code with absolute xpath that works fine when the span is directly inside of h4 but this isn't always case and cant depend on that.
And more important have some other similar methods and want to clarify what happens in this xpath implementations and how can I use it in the best way.
final Node nodeSpanPodzakonska = elementH4.selectSingleNode("span[@class='palnk']");
Danilo Cubrovic

Sorry. I will have to think about the XPath question in more detail.
As to the side by side comparison: I meant of - open source HTML parsers
http://java-source.net/open-source/html-parsers
and also of XML frameworks that support XPath (such as DOM4j vs XOM).
I am going to try HTMLParser with XOM, as I have, in informal speed testing, seen HTMLParser to be quite fast compared to others.
The reason I would like to have speed is that I am working on a Web automation toolkit:
www.mkosh.com
and it looks like I will be re-parsing the entire tree after many Javascript commands.
I would like to make this as speedy as possible. HTMLParser seems to win hands down, although if it does not work with real world HTML, that could be an issue.
I will have to test.
Thank you so much
Misha

Similar Messages

  • Dom4j InvalidXPathException problem

    Hi,
                    <textItem id="1">
                   <title>first</title>
                   <displayText>number one</displayText>
                   <displayGraphic filename="uno"/>
              </textItem>
    xp = DocumentHelper.createXPath("//textItem@id");When I run the above xpath expression on the xml code I get :
    org.dom4j.InvalidXPathException: Invalid XPath expression: //hotTextItem@id Unexpected '@'
    at org.dom4j.xpath.DefaultXPath.parse(DefaultXPath.java:360)
    at org.dom4j.xpath.DefaultXPath.<init>(DefaultXPath.java:59)
    at org.dom4j.DocumentFactory.createXPath(DocumentFactory.java:230)
    at org.dom4j.DocumentHelper.createXPath(DocumentHelper.java:121)
    I am sure that this is the correct xpath string to use. Is it?
    thanks,
    Hugh

    inabind wrote:
    I am sure that this is the correct xpath string to use. Is it?That looks remarkably silly, as the second sentence directly contradicts the first sentence. And you really know that it isn't correct, don't you? Try not to get caught up in wishful thinking and egoistic behaviour. It just gets in the way of problem-solving.
    Anyway, no, that isn't a valid XPath expression. (That's what the error message says.) I expect your next question would have been how to make it correct, but that can't be answered without knowledge of what the expression was intended to find.

  • Dom4j xpath prblem

    Hi ,
    I'm trying to parse the xml file below using dom4j xpath tool.
    however the java code below give me an exception :
         java.lang.NoClassDefFoundError: org/jaxen/JaxenException
             at org.dom4j.DocumentFactory.createXPath(DocumentFactory.java:230)
             at org.dom4j.tree.AbstractNode.createXPath(AbstractNode.java:207)
             at org.dom4j.tree.AbstractNode.selectNodes(AbstractNode.java:164)
             at com.sun.star.addon.sugarcrm.soap.Sugar.getSearchInfo(Sugar.java:213)
             at test.SugarTestSuite.testGetSugarSearchInfo(SugarTestSuite.java:108)
             at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
             at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
             at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
             at java.lang.reflect.Method.invoke(Unknown Source)
             at junit.framework.TestCase.runTest(TestCase.java:168)
             at junit.framework.TestCase.runBare(TestCase.java:134)
             at junit.framework.TestResult$1.protect(TestResult.java:110)
             at junit.framework.TestResult.runProtected(TestResult.java:128)
             at junit.framework.TestResult.run(TestResult.java:113)
             at junit.framework.TestCase.run(TestCase.java:124)
             at junit.framework.TestSuite.runTest(TestSuite.java:232)
             at junit.framework.TestSuite.run(TestSuite.java:227)
             at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:81)
             at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:38)
             at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
             at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:460)
             at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:673)
             at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:386)
             at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196)
         what am i doing wrong ?
    thanks for helping.
    java code:
      try {
                       if (sugarSearchInfoArray == null)
                             SAXReader reader = new SAXReader();
                             Document document = reader.read(Utils.getResourceURL("/SugarSoap.ArchiveSettings.xml"));
                            ArrayList mlist = new ArrayList();
                            List list = document.selectNodes( "//Module/" );
                            for (Iterator iter = list.iterator(); iter.hasNext(); ) {
                                Node node = (Node) iter.next();
                                String module = node.valueOf( "@name" );
                                String defName = module;
                                _logger.debug("module->"+defName);
                                String strIcon=node.valueOf( "@icon" );
                                int num2=Integer.parseInt(strIcon);
                                _logger.debug("icon num->"+num2);
                                List list3 = node.selectNodes( "/SearchFields/*" );
                                List list4 = node.selectNodes( "/DisplayFields/*" );
                                for (Iterator iter3 = list3.iterator(); iter3.hasNext(); ){
                                     Node child = (Node) iter3.next();
                                    String name = child.valueOf( "@name" );
                                    _logger.debug("search field->"+name);
                                    list3.add(name);
                                for (Iterator iter4 = list4.iterator(); iter4.hasNext(); ){
                                     Node child = (Node) iter4.next();
                                    String name = child.valueOf( "@name" );
                                    _logger.debug("display field->"+name);
                                    list4.add(name);
                                SugarSearchInfo info = new SugarSearchInfo(module, null, num2, (String[]) list3.toArray(new String[list3.size()]), (String[]) list4.toArray(new String[list4.size()]));
                                mlist.add(info);
                            Module_list _list = this.soap.get_available_modules(this.sessionid);
                            if (_list.getError().getNumber().equals("0"))
                                boolean flag2 = false;
                                SugarSearchInfo[] sList=(SugarSearchInfo[])mlist.toArray(new SugarSearchInfo[mlist.size()]);
                                for (SugarSearchInfo info2 : sList)
                                    for (String str5 : _list.getModules())
                                        if (info2.module.equals(str5))
                                            flag2 = true;
                                            break;
                                    if (!flag2)
                                        list.remove(info2);
                            sugarSearchInfoArray = (SugarSearchInfo[]) mlist.toArray(new SugarSearchInfo[mlist.size()]);
                  } catch (NumberFormatException e) {
                       // TODO Auto-generated catch block
                       e.printStackTrace();
                  } catch (RemoteException e) {
                       // TODO Auto-generated catch block
                       e.printStackTrace();
                  } catch (DocumentException e) {
                       // TODO Auto-generated catch block
                       e.printStackTrace();
                 return sugarSearchInfoArray;
             }   the xml file :
    <?xml version="1.0" encoding="utf-8" ?>
        <ArchiveOptions>
             <ArchiveModules>
                  <Module name="Contacts" icon="0">
                       <SearchFields>
                            <Field name="contacts.last_name"/>
                            <Field name="contacts.first_name"/>
                       </SearchFields>
                       <DisplayFields>
                            <Field name="last_name"/>
                            <Field name="first_name"/>
                            <Field name="salutation"/>
                            <Field name="account_name"/>
                       </DisplayFields>               
                  </Module>
                  <Module name="Accounts" icon="1">
                       <SearchFields>
                            <Field name="accounts.name"/>
                       </SearchFields>
                       <DisplayFields>
                            <Field name="name"/>
                       </DisplayFields>
                  </Module>
                  <Module name="Opportunities" icon="2">
                       <SearchFields>
                            <Field name="opportunities.name"/>
                       </SearchFields>
                       <DisplayFields>
                            <Field name="name"/>
                       </DisplayFields>
                  </Module>
                  <Module name="Cases" icon="3">
                       <SearchFields>
                            <Field name="cases.name"/>
                       </SearchFields>
                       <DisplayFields>
                            <Field name="name"/>
                       </DisplayFields>
                  </Module>
                  <Module name="Bugs" icon="4">
                       <SearchFields>
                            <Field name="bugs.name"/>
                       </SearchFields>
                       <DisplayFields>
                            <Field name="name"/>
                       </DisplayFields>
                  </Module>
                  <Module name="Leads" icon="5">
                       <SearchFields>
                            <Field name="leads.first_name"/>
                            <Field name="leads.last_name"/>
                            <Field name="leads.account_name"/>
                       </SearchFields>
                       <DisplayFields>
                            <Field name="last_name"/>
                            <Field name="first_name"/>
                            <Field name="account_name"/>
                       </DisplayFields>
                  </Module>
                  <Module name="Project" icon="6">
                       <SearchFields>
                            <Field name="project.name"/>
                       </SearchFields>
                       <DisplayFields>
                            <Field name="name"/>
                       </DisplayFields>
                  </Module>
                  <Module name="ProjectTask" icon="7">
                       <SearchFields>
                            <Field name="project_task.name"/>
                       </SearchFields>
                       <DisplayFields>
                            <Field name="name"/>
                       </DisplayFields>
                  </Module>
                  <Module name="Documents" icon="8">
                       <SearchFields>
                            <Field name="documents.document_name"/>
                       </SearchFields>
                       <DisplayFields>
                            <Field name="document_name"/>
                            <Field name="document_revision"/>
                       </DisplayFields>
                  </Module>
             </ArchiveModules>
        </ArchiveOptions>  

    thanks
    i added the missing jaxen.jar to classpath.
    now the error disappeared but I'm not getting the right results.
    i changed my code to this :
    if (sugarSearchInfoArray == null)
                         SAXReader reader = new SAXReader();
                         Document document = reader.read(Utils.getResourceURL("/SugarSoap.ArchiveSettings.xml"));
                        ArrayList mlist = new ArrayList();
                        List list = document.selectNodes( "//Module" );
                        for (Iterator iter = list.iterator(); iter.hasNext(); ) {
                            Node node = (Node) iter.next();
                            String module = node.valueOf( "@name" );
                            String defName = module;
                            _logger.debug("module->"+defName);
                            String strIcon=node.valueOf( "@icon" );
                            int num2=Integer.parseInt(strIcon);
                            _logger.debug("icon num->"+num2);
                            List list3 = document.selectNodes(node.getUniquePath()+"/SearchFields/descendant::*" );
                            _logger.debug("list3->"+list3.size());
                            for (Iterator iter3 = list3.iterator(); iter3.hasNext(); ){
                                 Node child = (Node) iter3.next();
                                String name = child.valueOf( "@name" );
                                _logger.debug("search field->"+name);
                                list3.add(name);
                            List list4 = document.selectNodes( node.getUniquePath()+ "/DisplayFields/descendant::*" );
                            for (Iterator iter4 = list4.iterator(); iter4.hasNext(); ){
                                 Node child = (Node) iter4.next();
                                String name = child.valueOf( "@name" );
                                _logger.debug("display field->"+name);
                                list4.add(name);
                            SugarSearchInfo info = new SugarSearchInfo(module, null, num2, (String[]) list3.toArray(new String[list3.size()]), (String[]) list4.toArray(new String[list4.size()]));
                            mlist.add(info);
                        Module_list _list = this.soap.get_available_modules(this.sessionid);
                        if (_list.getError().getNumber().equals("0"))
                            boolean flag2 = false;
                            SugarSearchInfo[] sList=(SugarSearchInfo[])mlist.toArray(new SugarSearchInfo[mlist.size()]);
                            for (SugarSearchInfo info2 : sList)
                                for (String str5 : _list.getModules())
                                    if (info2.module.equals(str5))
                                        flag2 = true;
                                        break;
                                if (!flag2)
                                    list.remove(info2);
                        sugarSearchInfoArray = (SugarSearchInfo[]) mlist.toArray(new SugarSearchInfo[mlist.size()]);
                        }unfortunately I get this exception :
    java.util.ConcurrentModificationException
         at java.util.AbstractList$Itr.checkForComodification(Unknown Source)
         at java.util.AbstractList$Itr.next(Unknown Source)
         at com.sun.star.addon.sugarcrm.soap.Sugar.getSearchInfo(Sugar.java:227)
         at test.SugarTestSuite.testGetSugarSearchInfo(SugarTestSuite.java:108)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
         at java.lang.reflect.Method.invoke(Unknown Source)
         at junit.framework.TestCase.runTest(TestCase.java:168)
         at junit.framework.TestCase.runBare(TestCase.java:134)
         at junit.framework.TestResult$1.protect(TestResult.java:110)
         at junit.framework.TestResult.runProtected(TestResult.java:128)
         at junit.framework.TestResult.run(TestResult.java:113)
         at junit.framework.TestCase.run(TestCase.java:124)
         at junit.framework.TestSuite.runTest(TestSuite.java:232)
         at junit.framework.TestSuite.run(TestSuite.java:227)
         at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:81)
         at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:38)
         at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
         at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:460)
         at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:673)
         at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:386)
         at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196)what's wrong this time with the code ?
    thanks much

  • Using DOM4J XPath

    IM going nuts trying to use DOM4J to query something so simple. Here is the input XML file and the code to run the XPath. If I loop through the document using the annoying element and node map thing it works fine and I can get all the nodes. But I want to run an XPath query right to the information I want. Firs time I tried without the URI nodes and this time I tried it with it. Still no luck.
    XML FILE
    <?xml version="1.0"?>
    <configs>
         <config SERVICE="Service Name">
              <detail name="key">value</detail>
         </config>
         <config SERVICE="ProcessErrors">
              <detail name="ErrorEmailAddresses">[email protected]</detail>
         </config>
         <config SERVICE="TestSQLErrors">
              <detail name="ErrorEmailAddresses">[email protected]</detail>
         </config>     
    </configs>CODE
    File fXmlFile = new File("n:\\config.xml");
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(fXmlFile);
    doc.getDocumentElement().normalize();
    XPath xpathNodes = new DefaultXPath("//configs/config[@SERVICE='ProcessErrors']/detail[@name='ErrorEmailAddresses']");
    HashMap<String, String> mapNodes = new HashMap<String,String>();
    xpathNodes.setNamespaceURIs(mapNodes);          
    Node exceptionNode = (Node)xpathNodes.selectSingleNode(doc);
    System.out.println(exceptionNode);exceptionNode is empty. If I run this same query on the same document in XML spy I get the value.???

    For obscure products it's generally better to ask on the forum or mailing list associated with that product. You're more likely to encounter people who have heard of the product and actually know something about it.
    On the other hand if it doesn't have a forum or mailing list, or there's no activity on that forum or mailing list, that's a hint you should consider using something more commonly used.

  • Can not find dom4j jar problem

    i create an application which use dom4j. This application works well with no problem. But when i try to call this application from my plugin ( a menu from workbench) an exception appears
    java.lang.NoClassDefFoundError: org/dom4j/io/SAXReader
    I already import dom4j to my plugin classpath.
    Any suggestion will be highly appreciated.

    anyone who have any idea bout it please help me. i got stuck with it for weeks. I still can not find a runable solution

  • Xindice - XPath Problem

    Hello,
    I've been using Xindice DB to manage XML files. Everything seemed to work well, but then i've run in some problems concering XPath queries.
    I have two "resources" (item1 and item2) for testing purposes in a collection named items. Both xml resources look like the following:
    <?xml version="1.0" encoding="UTF-8"?>
    <assessmentItemType title="item1" timeDependent="false"
      identifier="item1" adaptive="false"
      xmlns:ns2="http://www.imsglobal.org/xsd/imslip_v1p0"
      xmlns="http://www.imsglobal.org/xsd/imsqti_v2p1"
      xmlns:ns4="http://www.w3.org/1998/Math/MathML"
      xmlns:ns3="http://www.w3.org/1999/xlink" xmlns:ns5="http://www.w3.org/2001/XInclude">
      <itemBody id="itemBody1"/>
    </assessmentItemType>i (e.g.) want to get the id of the itemBody element, so i use the xpath query
    //itemBody/@id For a strange reason i don't get any results back.
    (I tested the query with the xpath trainer on http://www.write4food.orangegear.com/xptr.html to check if my xpath query was wrong, but it wasn't)
    If i just use
    /* as an xpath query, i get both resources (item1 and item2), which means that some xpath queries work.
    I'm fetching the data with the following code
    String query = "//itemBody/@id";
    XPathQueryService service = (XPathQueryService) col.getService("XPathQueryService", "1.0");
    ResourceSet resultSet = service.query(query);
    ResourceIterator results = resultSet.getIterator();
    while (results.hasMoreResources()) {
         Resource res = results.nextResource();
         System.out.println((String) res.getContent());
    }Has anyone an explanation for this behavior?
    Thanks in advance!
    Figured it out: Forgot to add the namespaces information. Now everything works fine...
    XPathQueryService service = (XPathQueryService) col.getService("XPathQueryService", "1.0");
    service.setNamespace("ns-prefix", "ns-url");n10e
    Message was edited by:
    n10e

    Create a DocumentFragment node from the Xml node to unmarshall.
    Unmarshall document node with method unmarshal(org.w3c.dom.Node node)
    Document document;
    Node node;//Node to unmarshall
    DocumentFragment df=
    document.createDocumentFragment();
    df.appendChild(node);
    JAXBContext jc = JAXBContext.newInstance("");
    Unmarshaller u = jc.createUnmarshaller();
    u.unmarshal(df);

  • XPath problems (or XKMS problems)

    Hi,
    I'm working with XKMS (XML Signature) package, and i have found some annoying problem (maybe someone has found it too and has solved it).
    When i create an XPath expression to point the Signature element of my XML file and try to construct a verifier which will check that signature, i get the next error:
    com.verisign.xpath.XPathException: /dsig:Signature does not contain Signature, found null
    at com.verisign.xmlsig.Verifier.checkIs(Verifier.java:169)
    at com.verisign.xmlsig.Verifier.spawnNewDigVerifier(Verifier.java:157)
    at com.verisign.xmlsig.Verifier.<init>(Verifier.java:147)
    at Negociador.main(Negociador.java:315)My XML document starts as follows:
    <?xml version="1.0" encoding="UTF-8"?>
    <dsig:Signature xmlns:dsig="http://www.w3.org/2000/09/xmldsig#">
       <dsig:SignedInfo xmlns:dsig="http://www.w3.org/2000/09/xmldsig#">
          <dsig:CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/>
          <d:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" xmlns:d="http://www.w3.org/2000/09/xmldsig#"/>
          <dsig:Reference URI="#ID0" xmlns:dsig="http://www.w3.org/2000/09/xmldsig#">
             <dsig:Transforms xmlns:dsig="http://www.w3.org/2000/09/xmldsig#">
                <dsig:Transform Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/>
             </dsig:Transforms>
             <dsig:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
             <dsig:DigestValue>iso+E+Q/i19YDd8I+GFCWqIRA4s=</dsig:DigestValue>
          </dsig:Reference>
       </dsig:SignedInfo>
       <dsig:SignatureValue xmlns:dsig="http://www.w3.org/2000/09/xmldsig#">Abfs4RrTcmXjhUa5pre+x/hxbfbNkljk79PKicTul76B6hX23v6/qWwxXHApH4yln67SYZMPELmWl3R4bq094UsEXiJPO8KdH25mDDpSDz76JG4a2Nmrn2PAIRjadGR9XhF+Mt4zSoYQqAy07fARCKhU9F36YBaoaVzti+nIa2o=</dsig:SignatureValue>
       <dsig:KeyInfo xmlns:dsig="http://www.w3.org/2000/09/xmldsig#"/>
       <dsig:Object Id="ID0" xmlns:dsig="http://www.w3.org/2000/09/xmldsig#">The XPath expression i am using is "/dsig:Signature". I've talked with some pals and they think this expression should work.
    Could someone tell me what am i doing wrong?
    Thanks in advance. David.

    I've already solved that problem. Seems that xpath expression was correct, thanks anyway. The problem was that XKMS seems not to understand Java XML parsers, so it needs its own one to understand the doc structure.
    Does anyone know why does this happen? Is it a codification matter?
    Thanks again.

  • Java XML Parser v2 xpath problem

    I have a lot of trouble using the xpath functionality. I want to get the name of different elements. I'm using some xpath expressions which in my opinion should work (see http://www.w3.org/TR/xpath ), but they don't. I'm calling XMLNode.selectSingleNode.
    For example :
    /*/name()
    name(/*[1])
    name(/*)
    name()
    I've tried those with Saxon and they do work. Using the Oracle implementation an exception is thrown on most expressions. So what's wrong here?
    Bye,
    Jan

    Consider this example
    --- Test.java -----
    import java.io.*;
    import javax.xml.transform.sax.SAXSource;
    import net.sf.saxon.sxpath.*;
    import oracle.xml.parser.v2.*;
    import org.w3c.dom.*;
    import org.xml.sax.InputSource;
    public class Test
    public Test() {
    try {
    DOMParser domParser = new DOMParser();
    domParser.parse(new FileReader("test.xml"));
    XMLDocument document = domParser.getDocument();
    InputSource is = new InputSource(new File("test.xml").toURL().toString());
    SAXSource source = new SAXSource(is);
    testXPathOracle(document,"count(//*)");
    testXPathOracle(document,"name(/*)");
    testXPathOracle(document,"name(/root)");
    testXPathOracle(document,"/*/name()");
    testXPathSaxon(source,"count(//*)");
    testXPathSaxon(source,"name(/*)");
    testXPathSaxon(source,"name(/root)");
    testXPathSaxon(source,"/*/name()");
    } catch(Exception e) {
    System.out.println(e.getMessage());
    public void testXPathOracle(XMLNode context, String xpath) {
    try {
    Node node = context.selectSingleNode(xpath);
    System.out.println(node.getNodeValue());
    } catch(Exception e) {
    System.out.println(e.getMessage());
    public void testXPathSaxon(SAXSource source, String xpath) {
    try {
    XPathEvaluator xpe = new XPathEvaluator();
    XPathExpression exp = xpe.createExpression(xpath);
    Object object = exp.evaluateSingle(source);
    System.out.println(object);
    } catch(Exception e) {
    System.out.println(e.getMessage());
    public static void main(String[] args) {
    Test test = new Test();
    --- test.xml -----
    <root>
         <element/>
    </root>
    Result is on my computer:
    Unknown expression at EOF: (count(//*))[1].
    Unknown expression at EOF: (name(/*))[1].
    Unknown expression at EOF: (name(/root))[1].
    Error in expression: '(/*/name())[1]'.
    2
    root
    root
    root
    I think the xpath expressions are valid. So what's wrong?

  • XPATH problem in Receiver Determination

    Hi Experts, I get stucked in the XPATH expression in the Receriver Determination(RD) :
    The input xml (default namespace settting) is like this :
    <?xml version="1.0" encoding="UTF-8" ?>
    <MT_XML_SENDER xmlns="http://test.com">
    <LAST_NAME>Bryant</LAST_NAME>
    <FIRST_NAME>Kobe10</FIRST_NAME>
    </MT_XML_SENDER>
    In the RD, I tried serveral XPATH expressions :
    /MT_XML_SENDER/LAST_NAME = Bryant
    /MT_XML_SENDER/LAST_NAME = "Bryant"
    /MT_XML_SENDER(LAST_NAME = \"Bryant\") EX
    But in every case, the PI always told me it could not find the receiver, I don't know what to do........
    (BTW,if I remove the condition, PI could work as desired, so it is 100% related to XPATH setting)
    Thanks very very much!!!!!
    Ray

    You probably noticed by yourself, but in the Condition Editor, it is necessary to set the namespace to a prefix and then create the XPath expression based on that prefix. i.e.
    /p1:MT_XML_SENDER/p1:LAST_NAME
    And on the prefix definitions, you set it to your namespace:
    p1 http://test.com
    Easiest way to do it is to go through the message structure, though, since it will fill the prefix automatically as per the definition in the message type in repository.
    Best regards,
    Henrique.

  • XPATH problems

    I use xpath to filter a xml document. When I use the xpath expressions from a main method everything works fine. But when I try to run my classes on through a servlet, the xpath returns nothing. I am using WSAD 5.0.1. Why would it not work on the server?

    I am using the xalan api to access xpath features.

  • Import Schema leads to XPath Problems

    Hallo,
    When using a bpel process where I have some schema definitions included, I'm not able to access the contents of variables with XPath.
    <schema attributeFormDefault="unqualified"
    elementFormDefault="qualified"
    targetNamespace="http://service.achrist.net/price/"
    xmlns="http://www.w3.org/2001/XMLSchema"
    xmlns:tns="http://service.achrist.net/price/"
    xmlns:md="http://service.achrist.net/masterdata/">
    <import schemaLocation="MasterData.xsd" namespace="http://service.achrist.net/masterdata/"/>
    <element name="PriceServiceProcessRequest">
    <complexType>
    <sequence>
    <element name="item" type="md:Item"/>
    <element name="supplier" type="md:Supplier"/>
    </sequence>
    </complexType>
    </element>
    </schema>
    The XPath expression in the BPEL process then crosses the two namespaces
    /client:PriceServiceProcessRequest/client:supplier/md:Name
    When using the expression inside an assign-activity, the bpel-engine claims
    "empty variable/expression result."
    A workaround for this is to copy paste the xsd types into the same namespace ... but rather ugly ...
    What is wrong with the imports ?

    Hello,
    I found one solution:
    Changing the way how elements are created to:
    <element name="PriceServiceProcessRequest">
              <complexType>
                   <sequence>
                        <element ref="md:ItemElement"/>
    <element ref="md:SupplierElement"/>
                   </sequence>
              </complexType>
         </element>
    ... now it works as expected...
    André

  • Xpath problems...please help

    Hi:
    i m new to xpath. i am trying to use xpath to select data from xhtml.Can i know how can select only one of the child ? take for example:
    - <table border="0" cellpadding="2" width="100%">
    + <tr>
    + <tr>
    + <tr>
    + <tr>
    - <tr>
    <td>Number of Kids</td>
    - <td>
    1
    - <small>
    Profile History
    </small>
    </td>
    </tr>
    + <tr>
    i only wan to get the info number of kids, so is 1. The xpath syntax that i put is ......tr[5]/td[2] but it give me all the children under td[2].....can anyone plz help?
    thank you

    hi emily_spt
    i m also doing the same project which converts html to xml in order to extract data.... from this website.:
    http://www-106.ibm.com/developerworks/web/library/wa-wbdm/
    i m not able to compile the programs XMLHelper.java and the other .
    can u plz illustrate the steps u had done to run the ..
    plzzzzzzzz reply as soon as possible

  • XMLBeans / XPath problem

    Hi,
    I'm getting java.lang.UnsupportedOperationException: This query is too complex to be processed. on the method call XmlObject[] h = doc.selectPath(queryText); I have googled the net looking for answers. I even downloaded XPath Explorer (Eclipse plugin) and my path works there for my XML file, so I'm stumped why it doesn't work in code. Please help!
    Here are the assets involved:
    The XML data file:
    <trx:box xmlns:trx="http://mysite.com/foo">
        <trx:transaction>
            <trx:id>100</trx:id>
            <trx:handler>Dog</trx:handler>
        </trx:transaction>
        <trx:transaction>
            <trx:id>200</trx:id>
            <trx:handler>Cat</trx:handler>
        </trx:transaction>
        <trx:transaction>
            <trx:id>300</trx:id>
            <trx:handler>Mouse</trx:handler>
        </trx:transaction>
    </trx:box>
    The XSD file:
    <xs:schema
        xmlns:xs="http://www.w3.org/2001/XMLSchema"
        xmlns:trx="http://mysite.com/foo"
        targetNamespace="http://mysite.com/foo"
        elementFormDefault="qualified">
         <xs:element name="box">
            <xs:complexType>
                <xs:sequence>
                    <xs:element name="transaction" type="trx:transaction" minOccurs="1" maxOccurs="unbounded"/>
                </xs:sequence>
            </xs:complexType>
        </xs:element>
       <xs:complexType name="transaction">
            <xs:sequence>
                <xs:element name="id" type="xs:string"/>
                <xs:element name="handler" type="xs:string"/>
            </xs:sequence>
        </xs:complexType>
    </xs:schema>
    The .xsdconfig file
    <xb:config
        xmlns:xb="http://xml.apache.org/xmlbeans/2004/02/xbean/config"
        xmlns:trx="http://mysite.com/foo">
        <xb:namespace uri="http://mysite.com/foo">
            <xb:package>com.mysite.foo</xb:package>
        </xb:namespace>
    </xb:config>
    The code (don't yell, it's just proof of concept code):
        public Handler getHandler(String id) throws Exception
            Handler handler = null;
            BoxDocument doc = BoxDocument.Factory.parse(file);
            String nsText = "declare namespace trx='http://mysite.com/foo' ";
            String pathText = "$this/trx:box/trx:transaction[trx:id=\"" + id + "\"]/trx:handler";
            String queryText = nsText + pathText;
            System.out.println(queryText);
            XmlObject[] h = doc.selectPath(queryText);  // fails here with "This query is too complex to be processed"
            Class ch = Class.forName(h[0].xmlText());
            handler = (Handler)ch.newInstance();
            return handler;
        }

    java.lang.UnsupportedOperationException: This query
    is too complex to be processed. In the source for XMLBeans, (xmlbeans-1.0.3/src/xmlstore/org/apache/xmlbeans/impl/store/XqrlDelegate.javaspecifically), you'll see that the rocket scientist who created this code throws an UnsupportedOperationException if it can't find the method for executing the query. The message in the exception is clearly designed to mislead his enemies.
    Saxon (http://saxon.sourceforge.net/) has 1000x more robust XQuery support and they have documentation for embedding it in your app.
    HTH,
    -- /v\atthew

  • Problem with selectNodes() in dom4j & jboss

    Hi,
    Iam facing some problem in parsing an xml file.
    The xml file is parsed perfectly and iam able to display the data inside it also using the rootelement.
    when iam calling selectNodes(Xpath expression), iam getting a ClassNotFoundException. i pasted Dom4j1.6.8.jar and jaxen-full.jar in JBoss server lib.
    Then also the problem is not solved. Here is my java file method, XML file and Exception.
    public static HashMap getDBConfigurtion() throws DAOException{
                XMLConfig xmlMain = new XMLConfig();
             String str = "../../../xml/config/config.xml";
            Document document = null;
            try {
              System.out.println("Inside GetDBConfiguration Try .. Before parse");
                document = xmlMain.parse(str);
                  System.out.println("INSIDE TRY AFTR DOC.. Nodes no.."+ document.nodeCount()+"Node Type is.."+document.getNodeType());
                //HashMap hash=new HashMap();
                //hash=document.
                return xmlMain.getConfig(document);
             } catch (Exception e) {
                 throw new DAOException("Excepiton in getDBConfiguration",e,false);
    public Document parse(String url) throws DocumentException {
            SAXReader reader = new SAXReader();
            Document document = reader.read(url);
            return document;
        public HashMap getConfig(Document document) throws DocumentException {
          //read the datasources
             System.out.println("XML CONFIG:: getConfig");/////////////////this is printed
            List lisNodes =  (List) document.selectNodes("//dbconfig/dbparams/datasources/datasource");//////////////ERROR HERE -NOT EXECUTED
            System.out.println("After selectNodes..size is"+lisNodes);
            for(int i=0;i<lisNodes.size();i++)
                 System.out.println("In for"+lisNodes.get(i));
            HashMap hmDataSources = new HashMap();
            for (Iterator iter = lisNodes.iterator(); iter.hasNext(); ) {
               Node n = (Node)iter.next();
               System.out.println("Node is.."+n.getName());
               hmDataSources.put(n.valueOf("@id"), n.getText());
               System.out.println("Datasources id:"+ n.valueOf("@id")+": Text :" + n.getText());
    /* begin config.xml*/
    <?xml version='1.0' encoding='UTF-8'?>
    <!DOCTYPE dbconfig SYSTEM "dbconfig.dtd">
    <dbconfig>
         <dbparams>
              <datasources>
                   <datasource Id="dsmysql">java:/MySQLDB</datasource>
              </datasources>
              <sqlproperties>
                   <sqlproperty id="maxfetchsize">10</sqlproperty>
                   <sqlproperty id="restrictchars">x</sqlproperty>
                   <sqlproperty id="deleteAllowed">false</sqlproperty>
              </sqlproperties>
         </dbparams>
         <!-- specifies the sqlrepositories locations -->
         <sqlrepositorypath>
              <sqlrepository Id="id1">../../../xml/module1/selectsql.xml</sqlrepository>
         </sqlrepositorypath>
    </dbconfig>
    /*end of file config.xml */
    Exception:-
    java.lang.NoClassDefFoundError: org/dom4j/xpath/DefaultXPath
    org.dom4j.DocumentFactory.createXPath(DocumentFactory.java:230)
    org.dom4j.tree.AbstractNode.createXPath(AbstractNode.java:207)
    org.dom4j.tree.AbstractNode.valueOf(AbstractNode.java:189)
    com.tsd.common.XMLConfig.getDBConfigurtion(Unknown Source)
    com.tsd.dao.DBDelegator.getSqlContext(Unknown Source)
    com.tsd.dao.DBDelegator.invoke(Unknown Source)
    BackingClass.display(Unknown Source)
    UserBean.display(Unknown Source)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.
    please give me some idea to resolve this.

    JBoss is using Dom4J for their own stuff: it probably supersedes your version. So you have to either:
    * forget Dom4J and use JAXP, which is standard and offer all you need,
    * replace Dom4J that ships with JBoss with yours (in JBOSS_ROOT/lib), but this might have adverse consequences

  • XPath Expression Problem

    Hi again,
    still a newb and stillsomequestions, but hope dies at last :)
    I want to extract values from a xml file which is stored in a table.
    i have the following code:
    COLUMN div DEFAULT
    SELECT extract(value(x), '//DIV/@ ID = ''FXAC93006ENC.0001.01.00''/text()').getStringVal() AS div
    FROM versuch2 x;
    With this code ive got the following Error Message: ORA:31012: Not supported XPath Statement.
    I tried this XPath statement in SlyXML and got a boolean:true result, so i think its not a xpath problem.
    Isthere a syntax problem?
    Thx for help!

    The correct syntax for fetching attributes is different from what you did.
    Not sure which syntax is the standard, but the Oracle Version seems more intuitive (too me). Why? Because an attribute is on the same hierachy level of the xml tag and therefore should not be queried with an additional /.
    SQL> with versuch2 as (select xmltype('<doc><div id="FXAC93006ENC.0001.01.00">Test</div></doc>') xmlcol from dual)
      2  SELECT extract(xmlcol, '//div[@id="FXAC93006ENC.0001.01.00"]/ text()').getStringVal() AS div
      3  FROM versuch2 x;
    DIV
    Test
    SQL>
    SQL> btw: W3C XPath Syntax stuff: http://www.w3.org/TR/xpath#predicates
    Message was edited by:
    Sven W.

Maybe you are looking for