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.

Similar Messages

  • 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

  • Xml parsing using dom4j

    I have some XML in String format, and I want to use the DocumentHelper.parseText() method on that string to parse it to Document format.
    I use it and it doesn't say anything about an error, however when I try to get "getelementroot()" and "getattributevalue" it gives me null.
    The XML looks like this:
    <Response status="1">
    <ERROR code="1">Offer is not available. </ERROR>
    <OFFER_ID>fPSC00010_PKG</OFFER_ID>
    </Response>
    I want to get the value of "status", i.e 1 in this case. So I do something like this:
    Element e = doc.getRootElement();
    String s = e.attributeValue("Status");
    Have I misunderstood something or what?

    Well I am not 100% sure why your code is causing a problem. I used dom4j 1 year ago.
    But I can give you my code snippet, the difference there to your snippet is that I first retrieved an Iterator over the Root element. And as I think the root element in your case is not the "Response" element it is more like a pointer to the start of the document. I am sorry for my vague explanation,it's too long age.
    But I am sure that you can use my example for your need effectively.
    public XMLMetaReader( String fileName )
            Document document = null;
            try
                SAXReader reader = new SAXReader( true );
                document = reader.read( fileName );
                root = document.getRootElement();
                createDBTree();
            catch ( DocumentException e )
                e.printStackTrace();
        public Map getSourceTables()
            return sourceTables;
        /** Return all tables which are set in the currently connected Database. */
        private void createDBTree() throws DocumentException
            for ( Iterator iterator0 = root.elementIterator( "database" ); iterator0.hasNext(); )
                Element databaseNode = ( Element ) iterator0.next();
                database = databaseNode.attributeValue( "ID" );
                // iterate through child elements of root with element name "table"
                for ( Iterator iterator = databaseNode.elementIterator( "table" ); iterator.hasNext(); )
                    Element tableNode = ( Element ) iterator.next();
                    Table table = new Table( tableNode.attributeValue( "ID" ) );
                    sourceTables.put( tableNode.attributeValue( "ID" ), table );
                    // iterate through child elements of root with element name "field"
                    for ( Iterator iterator2 = tableNode.elementIterator( "field" ); iterator2.hasNext(); )
                        Element fieldNode = ( Element ) iterator2.next();
                        Field field = new Field( fieldNode.attributeValue( "ID" ) );
                        field.setOriginalDomain( fieldNode.attributeValue( "datatype" ) );
                        if ( fieldNode.attributeValue( "default" ) != null )
                            String fieldValue = fieldNode.attributeValue( "default" );
                            if ( ( fieldValue ).equalsIgnoreCase( "NULL" ) )
                                field.setIsOriginalNullable( true );
                            else if ( ( fieldValue ).equalsIgnoreCase( "NOT NULL" ) )
                                field.setIsOriginalNullable( false );
                            else
                                field.setOriginalDefault( fieldValue );
                        table.addField( field );
                    for ( Iterator iterator2 = tableNode.elementIterator( "primarykey" ); iterator2.hasNext(); )
                        Element primaryNode = ( Element ) iterator2.next();
                        for ( Iterator iterator3 = primaryNode.elementIterator( "key" ); iterator3.hasNext(); )
                            Element keyNode = ( Element ) iterator3.next();
                            table.addPrimaryKey( keyNode.attributeValue( "field" ) );
                            Field primaryField = table.getField( keyNode.attributeValue( "field" ) );
                            primaryField.setIsOriginalPrimary( true );
                    for ( Iterator iterator2 = tableNode.elementIterator( "foreignkey" ); iterator2.hasNext(); )
                        Element foreignNode = ( Element ) iterator2.next();
                        ForeignKey foreignKey = new ForeignKey();
                        for ( Iterator iterator3 = foreignNode.elementIterator( "key" ); iterator3.hasNext(); )
                            Element keyNode = ( Element ) iterator3.next();
                            foreignKey.setOnField( keyNode.attributeValue( "field" ) );
                            System.out.println( keyNode.attributeValue( "field" ) );
                            foreignKey.setReferencedTable( keyNode.attributeValue( "references" ) );
                            System.out.println( keyNode.attributeValue( "references" ) );
                        for ( Iterator iterator3 = foreignNode.elementIterator( "onupdate" ); iterator3.hasNext(); )
                            Element onUpdateNode = ( Element ) iterator3.next();
                            foreignKey.setOnUpdate( onUpdateNode.attributeValue( "action" ) );
                        for ( Iterator iterator3 = foreignNode.elementIterator( "ondelete" ); iterator3.hasNext(); )
                            Element onDeleteNode = ( Element ) iterator3.next();
                            foreignKey.setOnDelete( onDeleteNode.attributeValue( "action" ) );
                        table.addForeignKey( foreignKey );
                    for ( Iterator iterator2 = tableNode.elementIterator( "index" ); iterator2.hasNext(); )
                        Element indexNode = ( Element ) iterator2.next();
                        Index index = new Index( indexNode.attributeValue( "name" ) );
                        index.setIsUNIQUE( ( indexNode.attributeValue( "unique" ) ).equalsIgnoreCase( "true" )  );
                        index.setIsDESC( ( indexNode.attributeValue( "ASC" ) ).equalsIgnoreCase( "true" )  );
                        /* index.setTable( tableNode.attributeValue( "ID" ) ); */
                        for ( Iterator iterator3 = indexNode.elementIterator( "indexfield" ); iterator3.hasNext(); )
                            Element indexFieldElement = ( Element )iterator3.next();
                            int position = Integer.parseInt( indexFieldElement.attributeValue( "position" ) );
                            index.addField( indexFieldElement.attributeValue( "field" ), ( short ) position );
                        table.addIndex( index );
                    for ( Iterator iterator2 = tableNode.elementIterator( "uniqueclause" ); iterator2.hasNext(); )
                        Element uniqueNode = ( Element ) iterator2.next();
                        UniqueConstraint uniqueConstraint = new UniqueConstraint();
                        for ( Iterator iterator3 = tableNode.elementIterator( "uniquefield" ); iterator3.hasNext(); )
                            Element uniqueFieldNode = ( Element ) iterator3.next();
                            uniqueConstraint.addField( uniqueFieldNode.attributeValue( "field" ) );
    }Hope it helps.
    Best regards
    Tarik

  • Equivalent of SQL JOINs using XML + XPath

    I have been working on a Java app for a while that takes user queries and searches various translations of the Bible. The data is stored in 66 .xml files, one per book of the Bible, and those files, in turn, are stored in a .jar file.
    The user may select 2 or more translations and see them in parallel. So for example, let's say that want Matthew chapter 1 and verses 1 to 10 from KJV and ASV. I simply use the following XPath expression: /book/chapter[@num=1]/verse[@num>=1 and @num<=10] . Then I use XPathFactory, XPath, compile() and evaluate() on Matthew.xml from kjv.jar and asv.jar.
    However, the problem is not so simple for keyword queries from the user. In such a case the tool searches for keywords in one translation and then finds the same verses from all subsequent translations. Here the XPath expression might be more like: /book/chapter/verse[contains(., 'keyword1') and contains(., 'keyword2')] for the first translation. However, if I ran the same query on subsequent translations they may or may not return the exact same set of verses (depending on language (English, Greek, Hebrew) and also on the dialect (Old English vs. Modern English)). So, my question is what is the most efficient way of obtaining the same verses from subsequent translations?
    I could simply look up the verses in the first translation, then use DOM API calls to find the chapter and verse numbers, and look those up in the other translations. But this seems tedious, SLOW, and possibly more error prone.
    Also, a second question: if I wanted to include a help file in my application's .jar file. How could I access that file programmatically? That is, how do I tell the application to look for "help.html" in the jar file so I can manipulate and/or display the contents to the user?
    And last question: since, I'm still learning my way around Java and XML, how would I go about programmatically applying a .xsl file to some given .xml input to produce HTML + CSS output? What classes, interfaces, etc. should I look up for this? And can anyone point me to sample code online for this?

    However, the problem is not so simple for keyword
    queries from the user. In such a case the tool
    searches for keywords in one translation and then
    finds the same verses from all subsequent
    translations. Here the XPath expression might be
    more like: /book/chapter/verse[contains(.,
    'keyword1') and contains(., 'keyword2')] for the
    first translation. However, if I ran the same query
    on subsequent translations they may or may not return
    the exact same set of verses (depending on language
    (English, Greek, Hebrew) and also on the dialect (Old
    English vs. Modern English)). So, my question is
    what is the most efficient way of obtaining the same
    verses from subsequent translations?
    I could simply look up the verses in the first
    translation, then use DOM API calls to find the
    chapter and verse numbers, and look those up in the
    other translations. But this seems tedious, SLOW,
    and possibly more error prone.There's nothing in XPath that I know of that helps with this. SQL is relational, XML is hierarchical. They're fundamentally different.
    Also, a second question: if I wanted to include a
    help file in my application's .jar file. How could I
    access that file programmatically? That is, how do I
    tell the application to look for "help.html" in the
    jar file so I can manipulate and/or display the
    contents to the user?If it's an HTML file, it's likely that you'll package it in a WAR file, along with the rest of your app. It's accessible as a URL that way.
    And last question: since, I'm still learning my way
    around Java and XML, how would I go about
    programmatically applying a .xsl file to some given
    .xml input to produce HTML + CSS output? What
    classes, interfaces, etc. should I look up for this?.xsl transformations are applied using XSL-T engines, like Apache's Xalan. You would embed the HTML that you want to inject the XML data into in the XSL-T stylesheet.
    That's one way. Another is to use a templating alternative like Velocity.
    And can anyone point me to sample code online for this?Try the Apache Xalan docs. Or this:
    http://www.cafeconleche.org/books/xmljava/chapters/ch17.html
    %

  • XML to Excel file using dom4j

    hi!
    i'm new with dom4j and i don't have any idea on how to do the following task:
    i have an xml document which i have to save as an excel file using dom4j. my problem is i also have to insert records in the middle of the file. is it possible?
    sample layout:
    Worksheet Header (also have to plot a value)
    Column Header (also have to plot a value)
    -- need to insert records here --
    Sub-total row
    Total row
    i would appreciate any help from you guys...
    thanks in advance...

    Hi there!
    First I haven't seen any application that uses dom4j to write excel's file, but I can recommend you to use Apache's POI to write and read from any excel's file, actually I'm working rigth now with it, and works fine with Office 2003.
    http://jakarta.apache.org/poi/hssf/
    For the XML you can use what ever you feel confortable with, dom4j, jdom, etc. I really like jdom thougth

  • XML Signature using an XPath filter

    I want to sign an XML document, just based on the content of a particular element in the document. Based on the jwsdp docs it looked pretty simple, but I'm getting strange results. I'll get the same digest value in the SignedInfo for different Xpath filter strings.
    Anybody out there have good luck trying to sign XML documents using Xpath filters?
    I'm using JDK 1.5.05 and JWSDP 1.6.
    Here is my simple XML doc
    <?xml version="1.0" encoding="UTF-8"?>
    <myns:whole_doc xmlns:myns="http://namespace.myns.com/test"
    attr1="attr_one" attr2="attr_two" attr3="attr_three">
    <myns:part_one attr="attr_one">
    <myns:tag1>this is part_one tag_one</myns:tag1>
    <myns:tag2>this is part_one tag_two</myns:tag2>
    </myns:part_one>
    <myns:part_two attr="attr_two">
    <myns:tag1>this is part_two tag_one</myns:tag1>
    <myns:tag2>this is part_two tag_two</myns:tag2>
    </myns:part_two>
    <myns:part_three attr="attr_three">
    <myns:tag1>this is part_three tag_one</myns:tag1>
    <myns:tag2>this is part_three tag_two</myns:tag2>
    </myns:part_three>
    </myns:whole_doc>
    When I use an XPath filter = "/myns:whole_doc/myns:part_one" I get the same digest as when I use "/myns:whole_doc/myns:part_two", which is the same digest when I don't use XPath filtering. See example output below
    <?xml version="1.0" encoding="UTF-8" ?>
    - <myns:whole_doc xmlns:myns="http://namespace.myns.com/test" attr1="attr_one" attr2="attr_two" attr3="attr_three">
    - <myns:part_one attr="attr_one">
    </myns:part_three>
    - <Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
    - <SignedInfo>
    <CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments" />
    <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#dsa-sha1" />
    - <Reference URI="">
    - <Transforms>
    <Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
    - <Transform Algorithm="http://www.w3.org/TR/1999/REC-xpath-19991116">
    <XPath>/myns:whole_doc/myns:part_two</XPath>
    </Transform>
    </Transforms>
    <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
    <DigestValue>9D5CFDkWd9bHx65txuHOeXWeTns=</DigestValue>
    </Reference>
    </SignedInfo>
    <SignatureValue>D686H//H5A0zDrlQx8+0fBNpVeJGgWdTXivlI8S/+WqB/E4oBYzeIQ==</SignatureValue>
    </Signature>
    </myns:whole_doc>

    It took me all day, but I did find the answer.
    When using XPath filters in references, you can't use XPath exactly the way you would use XPath to find nodes in a document. I can't exactly explain why, but it has to do with the fact that the XPath statement is acting as a filter.
    Anyway, to just include the part_one element from the following abbreviated XML
    <myns:whole_doc> .....
    <myns:part_one> ..... </myns:part_one>
    <myns:part_two> .... </myns:part_two>
    </myns:whole_doc>
    the XPath statement should be "ancestor-or-self::myns:part_one"
    to make sure that part_one was part of whole_doc you could use something like
    (ancestor-or-self::node() = /myns:whole_doc/myns:part_one)
    This allows me to sign a document, but still allow portions outside of whole_doc/part_one to change.

  • Sorting XML using DOM4J

    Hi All,
    Below is a sample XML which needs to be sorted based on the "id" attribute of the "key" element.
    <?xml version='1.0'?>
    <main>
    <key id='16066'>
    <key id='16061'>
    <key id='11'>
    <key id='1'>
    <key id='2'>
    <key id='1001'>
    </main>
    I am trying to sort the XML using the below function using DOM4J
    List xmlList = document.selectNodes("//main/key","@id")
    But the List is not sorted based on the number.
    I found that this does not happen even through XSLT because
    When sorting in default mode, the sorting is performed using alphabetic string comparisons. If numbers are to be sorted according to their numeric value, data-type must be set to "number".
    for example : "<xsl:sort data-type="number"/>"
    But, how do we do this using DOM4J.
    Please advice how to sort the numbers in an XML without using XSLT
    Thanks in advance,
    Raju

    Write your own code that manipulates the DOM.

  • Selecting nodes using an XPath expression

    Assuming that I have a DOM Document object containing a valid XML file, what is the quickest way to select a subset of nodes from the document using an XPath expression. I would like the results in either a NodeList object or another Document object.
    Microsoft has a way to do this using a single method named 'selectNodes'. Why is querying an XML document so hard to do using java? Am I missing something?

    In case you're using Xalan take a look at org.apache.xpath.XPathAPI. The function selectNodeList(...) probably does what you want.
    Good luck.

  • Maximum file handled using dom4j

    Hi,
    Wanna know whats the maximum xml file size that can be handled using dom4j.
    To be precise, I have a 1gb xml file that I wanna parse, I have implemented it using SAX, but wanna know if dom4j can be used?
    Regards,
    R

    Just try, you'll probably only be limited by available memory. I assume that building any kind of DOM tree of the document (be it org.w3c.dom or dom4j) will use more memory than the original file. So you'll need > 1 GB of memory for your file. If you have to handle files that big and don't absolutely need it all at the same time then SAX is probably the better solution as it doesn't require the whole file to be in memory at a time.

  • Using the XPATH expression function in Transformation activity

    Hi,
    I have to map the variable value(other than the source variable) to one of the node in the target variable in the transformation activity. For that I am using the XPATH expression function bpws:getVariableData ('variableName') and map it to corrsponding target node. But this mapping is not at all happening. The same prolem occurs while using function ora:getInstanceID() in transformation function. Then I could find a metalink note id: 387381.1,saying it as the bug in 10.1.2.2 BPEL PM, which they are covering in the next release. But our BPEL PM version is 10.1.3.3. But still the same type of problem occurs.
    Please let me know, is there are any solution for using the ora:getInstanceID() , bpws:getVariableData in Transformation activity.

    Hi,
    I dont understand why would you need to use the "bpws:getVariableData" function.
    When you are mapping a source-node to a target-node, it usually assigns the value in the source-node to the target-node, which is as good as using the "bpws:getVariableData" function.
    So, technically speaking you need to use this function explicitly to achieve that ...
    Also, if you want the instance-id, you can use the "ora:getInstanceId()" directly in the BPEL code than using it in the transformation.
    Regards,
    Madhu.

  • Error while using dom4j

    Hi
    I am using dom4j for generating xml file ,but when I am trying to run a batch(which invokes java file(uses dom4j)), it is giving me error as --> Exception in thread "main" java.lang.NoClassDefFoundError: org/dom4j/Branch
    I have set the jar file in the CLASSPATH and also put it in the server(weblogic) lib directory.Still I am getting the same problem.
    Server is weblogic and OS is windows.
    Please help
    Thanks
    Piyush

    What's a "batch"? You were talking about the classpath, then you switched to talking about Weblogic. It's not clear what is your context nor what you are trying to do.

  • How to use XML / XPath in JAVA (in 1.4) which third part component to use?

    How to use XML / XPath in JAVA (in 1.4)
    I'm absolutely novice in XML
    but I need to query XML using XPath
    As I understand XPath become avalible only in Java 1.5
    But I use 1.4 (project requirement)
    Which third part component could you recomend?

    Can anyone help me with this XPath query
    I get result [title: null]
    import java.io.*;
    import javax.xml.parsers.*;
    import org.xml.sax.*;
    import org.w3c.dom.*;
    import org.jaxen.*;
    import org.jaxen.dom.*;
    import org.jaxen.saxpath.*;
    import java.util.*;
    public class TestX {
         public void ggg() {
              try {
                   File f = new File("journal.xml");
                   DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
                   org.w3c.dom.Document doc = docBuilder.parse(f);
                   XPath xpath = new DOMXPath( "/journal/article/title" );
                   List result = (List) xpath.evaluate(doc);
                   System.out.println(result.get(0));
              } catch (Exception e) {
                       e.printStackTrace();
         public static void main(String[] args) {
              TestX tx = new TestX();
              tx.ggg();
    }journal.xml
    <journal>
        <article id="article.1">
            <title>Art1</title>
            <author>
               <first>Bob</first>
               <last>McWhirter</last>
            </author>
            <text>
            </text>
        </article>
        <article id="article.2">
            <title>Art2</title>
            <author>
               <first>James</first>
               <last>Strachan</last>
            </author>
            <text>
            </text>
        </article>
    </journal>

  • Use of Xpather with OATS.

    We have been using Selenium.
    Now we are learning OATS. Can we use the "XPather',FireBug with OATS.
    I assume we can use the isTextPresent, asserEquals etc with OATS tool.
    Is this correct.
    Regards

    Thanks for the reply Alex.
    I would like to know whether or not we can use Firebug,XPather tool (these attach to Firefox browser only). These are not related to OpenScript directly, though, the IDE/Interface is eclipse, it seems.
    Regards

  • What's wrong with my XPath statement using dom4j?

    I'm pretty new to XML. However, I did pick up a book and I'm pretty much through it. I got a copy of dom4j and I created a sample XML file. I'm able to parse the data and find out the child elements of root but I'm having problems with using XPath no matter what I do. Here's my code:
    import org.dom4j.*;
    import org.dom4j.io.*;
    import java.util.*;
    import java.io.*;
    public class XMLACL {
      org.dom4j.Document doc;
      org.dom4j.Element root;
      XMLACL(String x) {
        String tempFile = System.getProperty("user.dir") + "/winsudo.xml";
        tempFile = tempFile.replace('\\', '/');
        SAXReader xmlReader = new SAXReader();
        try {
          doc = xmlReader.read(tempFile);
        catch (Exception e) {}
        root = doc.getRootElement();
        //treeWalk();
        //iterateRootChildren("grant");
        XPath xpathSelector = DocumentHelper.createXPath("/grant[@prompt='no']");  
        List results = xpathSelector.selectNodes(doc);
        for (Iterator iter = results.iterator(); iter.hasNext(); ) {
         Element element = (Element) iter.next();
          System.out.println(element.getName());
    }And here's my XML:
    <?xml version="1.0" encoding="UTF-8"?>
    <config>
         <alias name="admin">
              <user>geneanthony</user>
              <user>mike</user>
              <user>rob</user>
         </alias>
         <grant prompt="no" runas="root" service="no">
              <user>geneanthony</user>
              <command>!ALL</command>
         </grant>
         <grant>
              <user>geneanthony</user>
              <group>users</group>
              <command>C:/Program Files/Mozilla Firefox/firefox.exe</command>
         </grant>
         <grant>
              <alias>admin</alias>
              <command>!Panels</command>
         </grant>
    </config>I'm currently getting this error:
    C:\Borland\JBuilder2005\jdk1.4\bin\javaw -classpath "C:\code\java\WinSudo\classes;C:\Borland\JBuilder2005\jdk1.4\jre\javaws\javaws.jar;C:\Borland\JBuilder2005\jdk1.4\jre\lib\charsets.jar;C:\Borland\JBuilder2005\jdk1.4\jre\lib\ext\dnsns.jar;C:\Borland\JBuilder2005\jdk1.4\jre\lib\ext\ldapsec.jar;C:\Borland\JBuilder2005\jdk1.4\jre\lib\ext\localedata.jar;C:\Borland\JBuilder2005\jdk1.4\jre\lib\ext\sunjce_provider.jar;C:\Borland\JBuilder2005\jdk1.4\jre\lib\im\indicim.jar;C:\Borland\JBuilder2005\jdk1.4\jre\lib\im\thaiim.jar;C:\Borland\JBuilder2005\jdk1.4\jre\lib\jce.jar;C:\Borland\JBuilder2005\jdk1.4\jre\lib\jsse.jar;C:\Borland\JBuilder2005\jdk1.4\jre\lib\plugin.jar;C:\Borland\JBuilder2005\jdk1.4\jre\lib\rt.jar;C:\Borland\JBuilder2005\jdk1.4\jre\lib\sunrsasign.jar;C:\Borland\JBuilder2005\jdk1.4\lib\dt.jar;C:\Borland\JBuilder2005\jdk1.4\lib\htmlconverter.jar;C:\Borland\JBuilder2005\jdk1.4\lib\tools.jar;C:\Borland\JBuilder2005\jdk1.4\jre\lib\jRegistryKey.jar;C:\Borland\JBuilder2005\jdk1.4\lib\hsqldb.jar;C:\Borland\JBuilder2005\jdk1.4\jre\lib\dom4j-1.6.1.jar;C:\Borland\JBuilder2005\jdk1.4\jre\lib\syntax.jar;C:\Borland\JBuilder2005\jdk1.4\jre\lib\IzPack-install-3.7.2.jar" winsudo.Main
    java.lang.NoClassDefFoundError: org/jaxen/JaxenException
         at org.dom4j.DocumentFactory.createXPath(DocumentFactory.java:230)
         at org.dom4j.DocumentHelper.createXPath(DocumentHelper.java:121)
         at winsudo.XMLACL.<init>(XMLACL.java:26)
         at winsudo.Main.main(Main.java:15)
    Exception in thread "main"
    Can someone tell me what's wrong with my code. None of the samples I've seen came with the XML files so I don't know if I when I start the XPATH I need to use / for the root element, or // or a forward slash and the root name. Can I please get some help!

    Thank you! I didn't haven Jaxen I thought everything was in the package and I must have missed it in the tutorials. That resolved the dropouts and I think I'm good know. I couldn't think for the life of me what I was doing wrong!

  • 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

Maybe you are looking for

  • Upgrade from Windows 7 pro to windows 8.1?

    Hi all, I've just purchased a brand new Elitebook 840 G1 for work, but upon receiving and open the first time, I noticed it come along with Windows 7 pro preinstalled. Are there any case I could "upgrade" it back to the windows 8.1 version as origina

  • How to Retrieve Purchase order TAX value price

    Hi, I want to retrieve Purchase order TAX value price from the purchase order is there any function module to retrieve this value.  Or from which table we can retrieve this value using purchase order no. Thanks in advance

  • Reg : Pull Chinese characters into XLS

    Hi Experts, I have to generate a report by pulling from tables to an Excel sheet. But i'm getting the Chinese characters as junk. FYI - I'm using PERL script for this report generation. Any idea regarding this ? TIA. Best Regards, Ranit B.

  • PrE 12.  How to deal with black screen "Created with Adobe Premiere Elements trial version"?

    I'm really considering purchasing PrE 12 and would like to try it out.  (I have another video editing software and would like to try this one.) When I add video, I get a black screen "Created with Adobe Premiere Elements trial version".  When I hit p

  • Missing Image Data in CS6 screen

    I'm am sporatically encountering missing image data when opened in the CS6 image screen.  Missing data is displayed with transparency grid.  The problem occurs opening an existing PSD or when launching CS6 from ACR.  Reloading the image may or may no