Using XPath for DOM traversal

This question falls into the category of 'I know it's possible, I just need to find the idom in Java'.
I'm coming from a MSFT world were the DOM-centric model of XML processing makes heavy use of XPATH for node selection. Basically using the method element.selectNodes(XPathExpresson) allows one to quickly extract the relevant subset of the parsed tree in the DOM as a nodeList. I've become accustomed to using XML for all strucutured storage that doesn't require a full database.
The W3C DOM Level 3 spec supports evaluateExpression() for this purpose, but I can't believe that Java developers are still using tree traversal waiting for the spec to be implemented. I suppose that I could use getNodesByTagName(), but this is a chainsaw, and I need a scalpel. Anyway, I'm trying to figure out how, exactly, this gets done in Java.
I figure the following are possibilities:
1) It's in JAXP and I missed it
2) One or more of the XML parsers supports XPATH as an extention
3) There's a common package that sits on top of the DOM Document.
4) There's a standard way to apply and XSLT methods to the DOM document
5) Something I've never thought of.
This is a generalized problem for me, so I can't rely on object serialization, Java-XML data mapping, etc. Any guidance would be greatly appreciated.

I've written a Config file reader for XML in java,
and it extracts values using XPath. This is
some of the code you'll need:
imports:
import javax.xml.transform.TransformerException;
import org.w3c.dom.*;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.apache.xerces.parsers.DOMParser;
import org.apache.xpath.XPathAPI;
import org.apache.xpath.objects.*;
Document doc=....;
* returns a single DOM Node from the config file.
public Node getNode(String xpath) throws ConfigException {
try {
return XPathAPI.selectSingleNode(doc, xpath);
} catch (TransformerException e) {
throw new ConfigException("Can't find '"+xpath+"' ("+e.getMessage()+")");

Similar Messages

  • Getting outOfMemory while using Xpath for 6MB file

    Hi ,
    Requirement:
    I have thousands of xml files of variable size (mostly around 5MB), Total size is around 20GB .The structure of xml content is as follows.
    filename: xaaaa
    <file>
    <page>
    <title>AmericanSamoa</title>
    <id>6</id>
    <revision>
    <id>133452270</id>
    <timestamp>2007-05-25T17:12:06Z</timestamp>
    <contributor>
    <username>Gurch</username>
    <id>241822</id>
    </contributor>
    <minor />
    <comment>Revert edit(s) by [[Special:Contributions/Ngaiklin|Ngaiklin]] to last version by [[Special:Contributions/Docu|Docu]]</comment>
    <text xml:space="preserve">#REDIRECT [[American Samoa]]{{R from CamelCase}}</text>
    </revision>
    </page>
    My task is to retrieve the ID , filename in which it exists and the position of node in the page, and i have to write it to a file.
    ex: 6:xaaaa:1
    My approach:
    I am using Xpath for this. The code is as follows.
    */*XPathReader.java*/*
    package preprocess;
    import java.io.IOException;
    import javax.xml.XMLConstants;
    import javax.xml.namespace.QName;
    import javax.xml.parsers.*;
    import javax.xml.xpath.*;
    import org.w3c.dom.Document;
    import org.xml.sax.SAXException;
    public class XPathReader {
    private String xmlFile;
    private Document xmlDocument;
    private XPath xPath;
    public XPathReader(String xmlFile) {
    this.xmlFile = xmlFile;
    initObjects();
    private void initObjects(){       
    try {
    xmlDocument = DocumentBuilderFactory.
                   newInstance().newDocumentBuilder().
                   parse(xmlFile);
    xPath = XPathFactory.newInstance().
                   newXPath();
    } catch (IOException ex) {
    ex.printStackTrace();
    } catch (SAXException ex) {
    ex.printStackTrace();
    } catch (ParserConfigurationException ex) {
    ex.printStackTrace();
    public Object read(String expression,
                   QName returnType){
    try {
    XPathExpression xPathExpression =
                   xPath.compile(expression);
    return xPathExpression.evaluate
                   (xmlDocument, returnType);
    } catch (XPathExpressionException ex) {
    ex.printStackTrace();
    return null;
    XpathReaderTest.java
    /* it takes directory name as argument, this directory contains xml file*/
    package preprocess;
    import java.io.*;
    import javax.xml.xpath.XPathConstants;
    import org.w3c.dom.*;
    public class XPathReaderTest {
    public XPathReaderTest() {
    public static void main(String[] args) throws IOException{
         if (args.length <= 0) {
              System.out.println(
              "Usage: java PreProcess dir_name"
              return;
              String dir=null;
              if (args.length >= 1) dir = args[0];
              int indexno=0;
              File directory = new File(dir);
              File[] files = directory.listFiles();
              FileWriter fstream = new FileWriter("index"+indexno+".txt");
         BufferedWriter out = new BufferedWriter(fstream);
         XPathReaderTest xt=new XPathReaderTest();
              /*for (int index = 0; index < files.length; index++)
                   System.out.println(files[index].toString());
              for (int index = 0,i=1; index < files.length; index++)
                   /*if(index/100>indexno){
                        indexno++;
                        out.close();
                        fstream = new FileWriter("index"+indexno+".txt");
                   out = new BufferedWriter(fstream);
                   xt.extract(files[index].toString(),index,i,out);
                   System.gc();
              out.close();
    public void extract(String completepath,int index,int i,BufferedWriter out)
    throws IOException
         System.out.println(index+" "+completepath);
              XPathReader reader = new XPathReader(completepath);
              String separator = File.separator;
              int pos = completepath.lastIndexOf(separator);
              String temp_fname=completepath.substring(0,pos);
              pos=temp_fname.lastIndexOf(separator);
              String f_name= completepath.substring(pos+1);
              i=1;
              while(true)
              String expression = "/file/page["+i+"]/id";
              String id_value= (String) reader.read(expression, XPathConstants.STRING);
              if(id_value=="")
                   break;
              out.write( id_value + ":"+ f_name+ ":"+i+ "\n" );
    i++;
    Problem:
    This code works fine for xml files < 6MB, but its giving outOfMemory for 6MB and above file.
    I have tried with -Xms256m -Xmx512m option.
    Please suggest the work around , or any modification to code that will resolve my problem.
    I am new to java world , so problem root cause will be very helpful for me.
    Thanks

    Hi ,
    Requirement:
    I have thousands of xml files of variable size (mostly around 5MB), Total size is around 20GB .The structure of xml content is as follows.
    /*filename: xaaaa*/
    <file>
    <page>
        <title>AmericanSamoa</title>
        <id>6</id>
        <revision>
          <id>133452270</id>
          <timestamp>2007-05-25T17:12:06Z</timestamp>
          <contributor>
            <username>Gurch</username>
            <id>241822</id>
          </contributor>
          <minor />
          <comment>Revert edit(s) by [[Special:Contributions/Ngaiklin|Ngaiklin]] to last version by [[Special:Contributions/Docu|Docu]]</comment>
          <text xml:space="preserve">#REDIRECT [[American Samoa]]{{R from CamelCase}}</text>
        </revision>
      </page>
    </file>My task is to retrieve the ID , filename in which it exists and the position of node in the page, and i have to write it to a file.
    ex: 6:xaaaa:1
    My approach:
    I am using Xpath for this. The code is as follows.
    */*XPathReader.java*/*
    package preprocess;
    import java.io.IOException;
    import javax.xml.XMLConstants;
    import javax.xml.namespace.QName;
    import javax.xml.parsers.*;
    import javax.xml.xpath.*;
    import org.w3c.dom.Document;
    import org.xml.sax.SAXException;
    public class XPathReader {
        private String xmlFile;
        private Document xmlDocument;
        private XPath xPath;
        public XPathReader(String xmlFile) {
            this.xmlFile = xmlFile;
            initObjects();
        private void initObjects(){       
            try {
                xmlDocument = DocumentBuilderFactory.
                   newInstance().newDocumentBuilder().
                   parse(xmlFile);           
                xPath =  XPathFactory.newInstance().
                   newXPath();
            } catch (IOException ex) {
                ex.printStackTrace();
            } catch (SAXException ex) {
                ex.printStackTrace();
            } catch (ParserConfigurationException ex) {
                ex.printStackTrace();
        public Object read(String expression,
                   QName returnType){
            try {
                XPathExpression xPathExpression =
                   xPath.compile(expression);
                return xPathExpression.evaluate
                   (xmlDocument, returnType);
            } catch (XPathExpressionException ex) {
                ex.printStackTrace();
                return null;
    XpathReaderTest.java
    /* *it takes directory name as argument, this directory contains xml file**/
    package preprocess;
    import java.io.*;
    import javax.xml.xpath.XPathConstants;
    import org.w3c.dom.*;
    public class XPathReaderTest {
        public XPathReaderTest() {
        public static void main(String[] args) throws IOException{
             if (args.length <= 0) {
                    System.out.println(
                     "Usage: java PreProcess dir_name"
                    return;
              String dir=null;
              if (args.length >= 1) dir = args[0];
              int indexno=0;
              File directory = new File(dir); 
              File[] files = directory.listFiles();
              FileWriter fstream = new FileWriter("index"+indexno+".txt");
             BufferedWriter out = new BufferedWriter(fstream);
             XPathReaderTest xt=new XPathReaderTest();
              /*for (int index = 0; index < files.length; index++)
                   System.out.println(files[index].toString()); 
              for (int index = 0,i=1; index < files.length; index++)
                   /*if(index/100>indexno){
                        indexno++;
                        out.close();
                        fstream = new FileWriter("index"+indexno+".txt");
                       out = new BufferedWriter(fstream);
                   xt.extract(files[index].toString(),index,i,out);
                   System.gc();
              out.close();
        public void extract(String completepath,int index,int i,BufferedWriter out)
        throws IOException
             System.out.println(index+" "+completepath);
              XPathReader reader = new XPathReader(completepath);
              String separator = File.separator;
              int pos = completepath.lastIndexOf(separator);
              String temp_fname=completepath.substring(0,pos);
              pos=temp_fname.lastIndexOf(separator);
              String f_name= completepath.substring(pos+1);
              i=1;
              while(true)
              String expression = "/file/page["+i+"]/id";
              String id_value= (String) reader.read(expression, XPathConstants.STRING);
              if(id_value=="")
                   break;
              out.write( id_value + ":"+ f_name+ ":"+i+ "\n" );
            i++;
    }Problem:
    This code works fine for xml files < 6MB, but its giving outOfMemory for 6MB and above file.
    I have tried with -Xms256m -Xmx512m option.
    Please suggest the work around , or any modification to code that will resolve my problem.
    I am new to java world , so problem root cause will be very helpful for me.
    Thanks

  • Using XPath for associatios into BPMN process??

    Hello everybody:
    I'm using Oracle SOA and BPM Suite 11.1.1.5
    I have a BPMN process that have an entry variable of type CBEFF_BIR_Type (the xml declaration is shown below)
    <xsd:complexType name="CBEFF_BIR_Type">
                     <xsd:sequence>
                        <xsd:element name="FormatOwner" type="xsd:positiveInteger" minOccurs="1" maxOccurs="1"/>
                        <xsd:element name="FormatType" type="xsd:positiveInteger" minOccurs="1" maxOccurs="1"/>
                        <xsd:element name="BIR_Information" minOccurs="0" maxOccurs="1">
                            <xsd:complexType>
                                <xsd:sequence>
                                    <xsd:element name="BIR_Info" type="iso-iec19785-3-7:BIRInfoType" minOccurs="0"
                                         maxOccurs="1"/>
                                    <xsd:element name="BDB_Info" type="iso-iec19785-3-7:BDBInfoType" minOccurs="0"
                                         maxOccurs="1"/>
                                    <xsd:element name="SB_Info" type="iso-iec19785-3-7:SBInfoType" minOccurs="0"
                                         maxOccurs="1"/>
                                </xsd:sequence>
                            </xsd:complexType>
                        </xsd:element>
                        *<xsd:element name="BIR" type="tns:BaseBIRType"/>*
                    </xsd:sequence>
                </xsd:complexType>* BaseBIRType xml declaration*
    <xsd:complexType name="BaseBIRType"/>According to the business logic that BIR sould contain a node of type URI_BIR or BinaryBIR (xml declaration is shown below), it will never a self BaseBIRType.
    <xsd:complexType name="URI_BIR">
                    <xsd:complexContent>
                        *<xsd:extension base="tns:BaseBIRType">*
                            <xsd:sequence>
                                <xsd:element name="URI" type="xsd:anyURI"/>
                            </xsd:sequence>
                        </xsd:extension>
                    </xsd:complexContent>
                </xsd:complexType>
    <xsd:complexType name="BinaryBIR">
                    <xsd:complexContent>
                        *<xsd:extension base="tns:BaseBIRType">*
                            <xsd:sequence>
                                <xsd:element name="Binary" type="xsd:base64Binary"/>
                            </xsd:sequence>
                        </xsd:extension>
                    </xsd:complexContent>
                </xsd:complexType>As you can see, the bolded code in the first block illustrate a node of type BaseBIRType and the bolded code in the second block shows that the complex type URI_BIR and BinaryBIR are an extension of BaseBIRType. So it looks like a inheritance, as I see it.
    Inside my process I need to know what kind of node is coming inside de BIR (URI or Binary) to copy it to the correct variable type. I've tryed using the XPath Expessions provided by the IDE (+ora:instanceOf(XpathExpression, QName)+) but I had no results.
    Please someone who can guide me?, I'll appreciate any help. I'm new in XPath.
    Regards,
    isabelbernely

    As I see it you should use transformations not associations in such case. Within transformation (xslt) you should use XPath expression to test which of the concrete instance of the base type you are dealing with and proceed accordingly. That's bit ugly (depending on actual subelements to distinguish types) so there are two alternatives:
    1. use xsi:type in xml instance - an attribute which will directly indicate the type of the element (many java xml binding frameworks can output such attribute while marshalling types to xml)
    2. remodel your xsd to use substitution groups - the construct is similar but due to nature of substitution groups each concrete type will have a separate named element - easy to distinguish later in transformation

  • XPath vs Dom Traversal

    I've heard XPath is more efficient than using the DOM api to traverse the XML. I am just curious if this is true or not.
    Thanks

    Yes , Xpath is faster . Probabaly , your DOM package supports XPath either directly or via an add-on, so you can use both.

  • How to use Xpath effectively with Java

    I am using Xpath for parsing a String with following syntax.This is a string suppose String xmlShopstring.
    <shopper>
                <upc>0123456789</upc>
                <desc>Planeters Peanutus</desc>
                <regprice>1.99</regprice>           
                <errorcode></errorcode>
            </shopper>In this case how can I use xpath parsing ?

    You can use classes from javax.xml, org.w3c.dom packages for performing XML operations in java.
    These APIs have very rich set of classes and methods for performing XML operations effectively.
    pravi.pravi wrote: how can I use xpath parsing?You need to parse XML String to org.w3c.dom.Document with use of following classes:
    javax.xml.parsers.DocumentBuilderFactory
    javax.xml.parsers.DocumentBuilderOnce you parse XML String to org.w3c.dom.Document you can use following classes and others for very effective XPath parsing.
    javax.xml.xpath.XPathFactory
    javax.xml.xpath.XPath
    javax.xml.xpath.XPathExpression
    javax.xml.xpath.XPathConstantsI have listed some classes which can help you to perform XPath parsing, you should also explore other classes in the API for more XML operations.
    Refer thread: http://forums.sun.com/thread.jspa?threadID=5357836
    Thanks,
    Tejas Purohit

  • Using XPath with the XML DOM

    I have just started to use the XML DOM API. One thing I cannot see yet is an easy way to use XPath to get the value of an element.
    What I would like to do is pass an XPath expression like this:
    \EDIFACT\ORDERS\NAD[2]\NAD01\NAD0102
    into a method, and get the value of the element returned to me.
    Does anybody know if there is a method of one of the DOM interfaces that would provide that kind of functionality, or am I going to have to traverse the nodes of the DOM tree manually to do this?
    BR,
    Tony.

    Hi Tony,
    I read your posted question - I have the same problem.
    I think that the method find_from_path_ns (or find_from_path) is the only "xpath"-like way to get a value.
    BUT the syntax is very limited so you cannot use all good features of xpath
    To traverse the nodes manually is (in my problem) unpractible - the xml-structures are different and it's horrible to traverse the tree.
    I need xpaths like ' //x/y[3]/z[a='MS']' . I know, the performance is not very good but for small XML-messages fast enough
    Do you have any solutions?
    regards
    Wolfgang Hummel

  • SSMS 2012:FOR XML PATH Using XPath Node Tests-Columnn name 'test()' contains an invalid XML identifier as required by FOR XML?

    Hi all,
    I am learning XPATH and XQUERY from the Book "Pro T-SQL 2008 Programmer's Guide" written by Michael Coles, (published by apress). I copied the Code Listing 12-8 FOR XML PATH Using XPath Node Tests (listed below) and executed it in my
    SQL Server 2012 Management Studio:
    --Coles12_8.sql // saved in C:/Documemnts/SQL Server Management Studio
    -- Coles Listing 12-8 FOR XML PATH Using XPATH Node Tests
    -- Retrieving Name and E-mail Addresses with FOR XML PATH in AdvantureWorks
    -- 16 March 2015 0935 AM
    USE AdventureWorks;
    GO
    SELECT
    p.NameStyle AS "processing-instruction(nameStyle)",
    p.BusinessEntityID AS "Person/@ID",
    p.ModifiedDate AS "comment()",
    pp.PhoneNumber AS "test()",
    FirstName AS "Person/Name/First",
    MiddleName AS "Person/Name/Middle",
    LastName AS "Person/Name/Last",
    EmailAddress AS "Person/Email"
    FROM Person.Person p
    INNER JOIN Person.EmailAddress e
    ON p.BusinessEntityID = e.BusinessEntityID
    INNER JOIN Person.PersonPhone pp
    ON p.BusinessEntityID = pp.BusinessEntityID
    FOR XML PATH;
    I got the following error message:
    Msg 6850, Level 16, State 1, Line 2
    Column name 'test()' contains an invalid XML identifier as required by FOR XML; '('(0x0028) is the first character at fault.
    I have no ideas why I got this error message.  Please kindly help and advise me how to resolve this error.
    Thanks in advance,  Scott Chang

    Hi Michelle, Thanks for your nice response.
    I corrected the mistake and executed the revised code. It worked nicely.
    I just have one question to ask you about the appearance of the xml output of my Co;les12_8.sql:
    <row>
    <?nameStyle 0?>
    <Person ID="1" />
    <!--2003-02-08T00:00:00-->697-555-0142<Person><Name><First>Ken</First><Middle>J</Middle><Last>Sánchez</Last></Name><Email>[email protected]</Email></Person></row>
    <row>
    <?nameStyle 0?>
    <Person ID="2" />
    <!--2002-02-24T00:00:00-->819-555-0175<Person><Name><First>Terri</First><Middle>Lee</Middle><Last>Duffy</Last></Name><Email>[email protected]</Email></Person></row>
    <row>
    <?nameStyle 0?>
    <Person ID="3" />
    <!--2001-12-05T00:00:00-->212-555-0187<Person><Name><First>Roberto</First><Last>Tamburello</Last></Name><Email>[email protected]</Email></Person></row>
    <row>
    <?nameStyle 0?>
    <Person ID="4" />
    <!--2001-12-29T00:00:00-->612-555-0100<Person><Name><First>Rob</First><Last>Walters</Last></Name><Email>[email protected]</Email></Person></row>
    <row>
    <?nameStyle 0?>
    <Person ID="5" />
    <!--2002-01-30T00:00:00-->849-555-0139<Person><Name><First>Gail</First><Middle>A</Middle><Last>Erickson</Last></Name><Email>[email protected]</Email></Person></row>
    <row>
    <?nameStyle 0?>
    <Person ID="6" />
    <!--2002-02-17T00:00:00-->122-555-0189<Person><Name><First>Jossef</First><Middle>H</Middle><Last>Goldberg</Last></Name><Email>[email protected]</Email></Person></row>
    <row>
    <?nameStyle 0?>
    <Person ID="7" />
    <!--2003-03-05T00:00:00-->181-555-0156<Person><Name><First>Dylan</First><Middle>A</Middle><Last>Miller</Last></Name><Email>[email protected]</Email></Person></row>
    <row>
    <?nameStyle 0?>
    <Person ID="8" />
    <!--2003-01-23T00:00:00-->815-555-0138<Person><Name><First>Diane</First><Middle>L</Middle><Last>Margheim</Last></Name><Email>[email protected]</Email></Person></row>
    <row>
    <?nameStyle 0?>
    <Person ID="9" />
    <!--2003-02-10T00:00:00-->185-555-0186<Person><Name><First>Gigi</First><Middle>N</Middle><Last>Matthew</Last></Name><Email>[email protected]</Email></Person></row>
    <row>
    <?nameStyle 0?>
    <Person ID="10" />
    <!--2003-05-28T00:00:00-->330-555-2568<Person><Name><First>Michael</First><Last>Raheem</Last></Name><Email>[email protected]</Email></Person></row>
    <row>
    <?nameStyle 0?>
    <Person ID="11" />
    <!--2004-12-29T00:00:00-->719-555-0181<Person><Name><First>Ovidiu</First><Middle>V</Middle><Last>Cracium</Last></Name><Email>[email protected]</Email></Person></row>
    <row>
    I feel this xml output is not like the regular xml output.  Do you know why it is diffrent from the regular xml xml output?  Please comment on this matter.
    Thanks,
    Scott Chang
    What do you mean by regular xml document? Are you referring to fact that its missing a root element? if yes it can be added as below
    USE AdventureWorks;
    GO
    SELECT
    p.NameStyle AS "processing-instruction(nameStyle)",
    p.BusinessEntityID AS "Person/@ID",
    p.ModifiedDate AS "comment()",
    pp.PhoneNumber AS "text()",
    FirstName AS "Person/Name/First",
    MiddleName AS "Person/Name/Middle",
    LastName AS "Person/Name/Last",
    EmailAddress AS "Person/Email"
    FROM Person.Person p
    INNER JOIN Person.EmailAddress e
    ON p.BusinessEntityID = e.BusinessEntityID
    INNER JOIN Person.PersonPhone pp
    ON p.BusinessEntityID = pp.BusinessEntityID
    FOR XML PATH('ElementName'),ROOT('RootName');
    replace ElementName and RootName with whatever name you need to set for element as well as the root element
    Please Mark This As Answer if it solved your issue
    Please Vote This As Helpful if it helps to solve your issue
    Visakh
    My Wiki User Page
    My MSDN Page
    My Personal Blog
    My Facebook Page

  • Using Xpath in Receiver Determination for greater than 500

    Hi,
    I am trying to use Xpath in the receiver Determination step and I want to check a field which is at item level and comes multiple times(0-unbounded) greater than 500.I tried with different options per SDN blogs,Xpath functions,but still I couldn't able to get what i am trying.I want to process the message when "quantity" is greater than 500,else I want to ignore the message with no errors.
    I gave like this    /p1: /LIST/item[quantity>499]     EX
    item loop is 0-unbounded and I need to check for every quantity.I selected the check box multi line as well.
    I played around different options,but still did not get what I am looking for.
    please suggest in this regard ,how I need to give the expression.
    Thank you,
    Sri

    Hi,
    For validating that the item field is occuring more than 500 times you need to choose the
    2.The exact XPath would be in your case *(/p1: /LIST/itemquantity[499]EX)*
    This means if the 500 th occurance of the item exists then the condition satisfies that is always true for 500 and above occurance of the item.
    Please revert if the suggestion proves to be helpful.
    cheers,
    Abhishek.
    Edited by: Abhishek  Paul on May 6, 2010 10:55 PM
    Edited by: Abhishek  Paul on May 6, 2010 11:02 PM
    Edited by: Abhishek  Paul on May 6, 2010 11:08 PM

  • Use of range in case of XPATH for receiver determination.

    Hi Experts,
    I need to achieve the following using standard receiver determination.
    The material number in the source message structure has to lie within a perticular range and that should decide the receiver of the message.
    For example:
    MT_SRC
    |---- Ele1
    |----
    MaterialNo.
    If MaterialNo is between 100000100 and 100001000 then it should be sent to BS_TGT1 else it should be sent to BS_TGT2.
    Is it possible to achieve this using the standard conditional receiver determination using XPATH and if yes, how exactly?
    Regards,
    Amol

    Hi Amol,
    I think its possible. Never tried though for a range.
    Go through this link and check out what is described under the section "Notes Regarding the Use of XPath Expressions"
    http://help.sap.com/saphelp_nw04/helpdata/en/43/a513f2632c332ce10000000a11466f/frameset.htm
    I am not sure whether it will work for two conditions though, i.e. for a range( Greater than 100000100, less than 100001000).
    Just try and let us know.
    Regards,
    Sanjeev.

  • There are a sample for loop data out using xpath-querie?

    hello,
    i have a web service that contains multiple rows. i transfered these data in a variable tInput. Now i want to transfer these data in a output variable.
    Is There a sample or tutorial, that shows how to loop data out of a variable (array) in a
    second variable using xpath-querie?
    regards,
    rala

    Hi,
    thanks for the Link, but it doesn't work at all.
    I have a variable tOutput with follow content:
    tOutput>
    <part name="parameters" >
    <SchedulForwardResponse>
    <SchedulForwardResult>
    <ArrayType>
    <plnnr>50001203</plnnr>
    <vornr>1</vornr>
    <starttime>20.08.2006 09:00:00</starttime>
    </ArrayType>
    <ArrayType>
    <plnnr>50001203</plnnr>
    <vornr>2</vornr>
    <starttime>20.08.2006 09:10:00</starttime>
    </ArrayType>
    <ArrayType>
    <plnnr>50001203</plnnr>
    <vornr>3</vornr>
    <starttime>20.08.2006 09:35:00</starttime>
    </ArrayType>
    </SchedulForwardResult>
    </SchedulForwardResponse>
    </part>
    </tOutput>
    I want to copy these content in the output Variable of my BPEL Prozess. But just the first <ArrayType> is copy to output:
    <ArrayTpe>
    <plnnr>50001203</plnnr>
    <vornr>1</vornr>
    <starttime>20.08.2006 09:00:00</starttime>
    </ArrayType>
    The other two <ArrayType> fail.
    I create 3 variables:
    <variable name="bufferOutput" messageType="ns0:SchedulForwardSoapOut"/> (MessageType of the invokeing WS)
              <variable name="count" type="xsd:integer"/>
              <variable name="n" type="xsd:integer"/>
    Count and n are counter for the while loop. Count is initial 1. For n i have follow expression:
    <assign name="prepareLoop">
    <copy>
    <from expression="ora:countNodes('bufferOutput','parameters','/ns0:SchedulForwardResponse/ns0:SchedulForwardResult/ns0:ArraySchedulType[1]')"></from>
    <to variable="n"/>
    </copy>
    </assign>
    In the BPEL Console i saw, that the value of n is1 and not 3 as i thought. When i set ora.countNodes to SchedulForwardResult n is null in the console.
    Does anybody try befor to copy such a content of a variable into another variable or has a idea how i can implement these?
    regards,
    rala

  • How to use XPath with Namespaces in the xml ?

    Hi all,
    I need to reference a certain Node in a Document using XPath notation.
    The problem is the the XML Document contains Namespaces inside it
    f.e.
    <xn:SubNetwork id="JRANM">
        <xn:VsDataContainer id="1">
           <xn:vsDataType>vsDataAreas</xn:vsDataType>
        </xn:VsDataContainer>
    </xn:SubNetwork >Using DOMXPath (from weblogic.xml.xpath)
      DOMXPath xPath = new DOMXPath("xn:SubNetwork/*");
      Set nodeset = xPath.evaluateAsNodeset(this.xmlRootElement);When I Iterate through the Set I can see it's empty.
    (On the other hand without namespaces everything is fine.)
    So how can I reference a Node that contains a namespace in it ?
    Thanks a lot
    Francesco

    We use the following class to perform XPath Queries on our XmlBean objects.
    Hope this helps,
    Craig
    import java.util.Set;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import org.apache.xmlbeans.XmlException;
    import org.w3c.dom.Document;
    import weblogic.xml.util.StringInputStream;
    import weblogic.xml.xpath.DOMXPath;
    * Class to encapsulate API specific (i.e. weblogic) XML functions
    public class XmlUtil {
         * Returns a set containing objects of type reflected in the query.<br/>
         * e.g.<br/>
         * /saur:tree/saur:treeNode[@label='My Reports']<br/>
         * Returns a Set of TreeNode objects<br/>
         * Sample Code: <br/>
         * <code>
         * Set set = XmlUtil.executeXPathQuery( myQuery, tree.xmlText());
         * for( Iterator iter = set.iterator(); iter.hasNext();) {
         *     TreeNode node = TreeNode.Factory.parse((Node)iter.next());
         *     // Do whatever...
         * </code>
         * @param query
         * @param xml
         * @return
        public static Set executeXPathSetQuery( String query, String xml) throws XmlException {
            try {
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();   
                factory.setNamespaceAware(true);
                DocumentBuilder builder = factory.newDocumentBuilder();
                StringInputStream in = new StringInputStream(xml);
                Document doc = builder.parse(in);
                DOMXPath xQuery =  new DOMXPath(query);
                return xQuery.evaluateAsNodeset(doc);
            catch(Exception x) {
                throw new XmlException("Error running XPath query", x);
    }

  • DOM Traversal and API documentation (missing?)

    Dear Community,
    I recently dived into the world of XML. So far I have done some reading and try-outs. What I am wondering about now is:
    Why are there packages for org.w3c.dom.html or events or ls or traversal etc given to me when I am importing them in eclipse that are not given in the API specifications?
    For instance. I wanted to try some stuff with the traversal Module of DOM. Therefore I have to import org.w3c.dom.traversal.*
    Well, this works fine. I was able to play around with some examples. But when I tried to find this package in the API specifications, I didn't find it. There were evens and ls etc...but traversal didn't show up!
    So, is there a reason that some packages with their interfaces are documented and others are not? And why are there packages available when they are not documented, at all? Yes, I know. I could got to w3c.org and have a look there since this is will give me all the infos I need. But, frankly, I don't understand it. If one would argument this way, then why put in the w3c package at all?
    But maybe there is a reason for this which I am not aware of. Or is there any extra API available compareable to the APIs for JSP or Java Servlets? These are extra packages and, of course, extra technologies since one needs Tomcat etc...
    So, maybe someone here could enlighten me? :-)
    Regards
    Marcel

    Not all classes are necessarily documented. For example sometimes the interface is documented, and the implementations are not, for a variety of reasons but largely because you're supposed to work with the interface only.
    However in this case, I'm guessing that you're using an added library, and you're looking at the documentation for something else.

  • XPATH vs DOM  tests acomplishied

    hi, i performed some test trying to select one node in a document with 10000 nodes (<name first="ssss" last="sss">) and the test said:
    [bold]Using xpath[bold]
    String xpath = "/doc/name[@first=\"Rodrigo\"]";
    Node node = XPathAPI.selectSingleNode(doc, xpath);[bold]it delay like 1970 milliseconds[bold]
    [bold]Using dom[bold]
    NodeList nodeList = (NodeList)doc.getElementsByTagName("name");
        int length = nodeList.getLength();
        for (int i = 0; i < length; i++) {
          Element node = (Element)nodeList.item(i);
          String name = node.getAttribute("first");
          if (name.equals("Rodrigo")) {
            break;
        }[bold]it delay like 1010 milliseconds[bold]
    HOW CAN IT BE ?????
    xpath is more slower than dom ??????
    thanks
    Rodrigo Gonzalez Asensio
    Researcher & Developer
    Buenos Aires - Argentina

    Hello Rodrigo,
    I shall not be surprised with your result. DOM builds a tree and keeps it in the memory.
    While (depending upon the XSLT engine) XSLT prredominantly uses SAX. SAX if fast for through reading. But if the application requires data that cannot be retrieved in one pass multiple passes are required (I do not know the exact structure of your document). This multiple pass does consume longer time.
    DOM takes a huge amount of memory - but nobody ever accused it to be very slow, sepecially if iterative reading is involved.
    Thus, your result may be entirely correct. If I were you, I would also check the configuration and environment of the system.
    If you require clarification, please contact me [email protected]
    Ironluca

  • Dom traversal

    I've used sun's xml parser and it had a very handy TreeWalker class for retrieving nodes from a DOM tree.
    This is some of the code I'm working with
    I'm trying to use schemas....
    XSDBuilder builder = new XSDBuilder( );
    URL url1, url2;
    try{
    url1 = new URL( "report.xsd" );
    catch( MalformedURLException e ){
    return;//failed
    XMLSchema schamadoc =(XMLSchema)builder.build(url1);
    DomParser dp = new DomParser( );
    try{
    url2 = new URL( "report.xml" );
    catch( MalformedURLException e ){
    return;//failed
    dp.setXMLSchema( schamadoc );
    dp.setValidationMode( XMLParser.SCHEMA_VALIDATION );
    dp.setError( System.out );
    try{
    NodeFactory factory = new NodeFactory();
    dp.setNodeFactory( factory );
    dp.parse( url2 );
    //HOW DO I USE THE FACTORY NOW TO TRAVERSE
    //THE DOM???
    catch( ....a bunch of exceptions
    So basically, how do I then use the NodeFactory to traverse the DOM that it has? Does oracle produce a nice tree walker utility?
    Any help would be appreciated!
    null

    Not all classes are necessarily documented. For example sometimes the interface is documented, and the implementations are not, for a variety of reasons but largely because you're supposed to work with the interface only.
    However in this case, I'm guessing that you're using an added library, and you're looking at the documentation for something else.

  • How to retrieve value of attribute using xPath ?

    Hello experts,
    I have a following xml chunk
    <image file="/articles/engineering/boxerengine/preview_282x160.jpg">
    <tout name="copyright"></tout>
    <tout name="license"></tout>
    <tout name="photographer"></tout>
    <tout name="description"></tout>
    </image>
    I want to retrieve value of attribute file from absolute node image.
    I tried using xpath='/image/@file' It gives output as file="/articles/engineering/boxerengine/preview_282x160.jpg"
    I just want value "/articles/engineering/boxerengine/preview_282x160.jpg"
    I tried using xpath='/image/@file/text()' . It does not work
    Following is the java code. I am using XOM parser.
    java code :
    Builder parser = new Builder();
    Document doc = parser.build(xmlFile);
    Nodes titles = doc.query(xPath);
    //xpath = ''/image/@file/text()"     
    for (int i = 0; i < titles.size(); i++) {
    strChunk = strChunk.append(titles.get(i).toXML());     
    return strChunk.toString();
    Please help.
    Thanks,
    Sandeep Parmar

    Hi Sandeep,
    Using XPath and XPathExpression you can evaluate XPath queries on Document. have a look at code given bellow:
    // Building Document from XML File
    org.w3c.dom.Document imageDoc = builder.parse(xmlFile);
    // getting new instance of XPath
    javax.xml.xpath.XPath xpath = javax.xml.xpath.XPathFactory.newInstance().newXPath();
    // Building XPathExpression by compiling XPath query
    javax.xml.xpath.XPathExpression xPathExp = xpath.compile("/image/@file");
    // Evaluting XPath Expression on Document
    String imagePath = (String) xPathExp.evaluate(imageDoc, javax.xml.xpath.XPathConstants.STRING);
    // Priting image path it will print : "/articles/engineering/boxerengine/preview_282x160.jpg", if you try with data given in your post.
    System.out.println(imagePath); Hope this will help.
    thanks,
    Tejas Purohit

Maybe you are looking for

  • Real tough data retrieval - assistance needed

    Late 2011 Macbook Pro with 500GB hard drive Lion 10.7 One morning out of absolutely nowhere I get this grey screen with a flashing question mark folder. I take it to the geniuses at the Apple store and they tell me my hard drive has failed (no explan

  • Org.xml.sax.SAXParseException

    Hi All, I am trying to parse an xml file whcih contains some special characters like "&" using DOM parser. So, i am gtting the saxparse exception "The reference to entity "T" must end with the ';' delimiter" Is there any way to overcome this exceptio

  • How to use MSCOMM with teststand

    Hello All,        I want to communicate with serial port via MSCOMM component in teststand,And I have already regestered MSCOMM in PC.But I can't find it in "automation server" on the module tab.        Look forward to your reply.Thanks. BR

  • VME PCI-6200 hard drive interface cable identification

    Hopefully someone on this forum still uses the VME PCI-6200.  I'm looking for a replacement hard drive interface cable, 50-pin female-female, connecting a 2.5" PATA hard drive to the PCI-6200 board.  Does anyone know the cable standard or where a rep

  • HTMLB Tableview: questions..;

    Hello, Simply I output my table as follows : <htmlb:form>   <htmlb:tableView id              = "tv1"                    visibleRowCount = "10"                    selectionMode   = "lineEdit"                    table           = "<%=mytable%>"