Read xml using xpath in java

Hi ALL,
I have a xml as follows:
<AAA>
<BBB>
<CCC>xyz</CCC>
<DDD>abc</DDD>
</BBB>
</AAA>
Now using any of the java class, i just need read the value of "CCC" as follows:
(i.e using xpath i need to read the value)
String val = x.somemethod("/AAA/BBB/CCC");
Thanks!

In case you're curious - here's the dom4j equivalent of dvohra09's sample code.
SAXReader saxReader = new SAXReader("org.apache.xerces.parsers.SAXParser");
Document doc = saxReader.read(source); //Where source is your file, input source, input stream, reader, or url
String value = doc.valueOf("//AAA/BBB/CCC"); //Result given the xml from OP = 'xyz'OK - not much difference with this simple example but if you haven't settled on an API, dom4j is worth looking at (IMHO).
&#8734; brewman &#8734;

Similar Messages

  • Write XML using XPath

    Hi,
    I have a problem. I need to WRITE a XML using XPath.
    Supose that XPath String : "/clients/client/name"
    Equivalent XML :
    <clients>
    <client>
    <name></name>
    </client>
    <clients>
    Please, helpme ...
    The XPath Strings are dinamic, there are lot of combinations.
    Is there an API (free ?) that support this ?
    Thankz

    Normally XPath is used for searching existing XML documents, not for creating new ones. So it's unlikely that anything exists to do what you ask. But not impossible, people do the strangest things. Have you searched Google?
    Of course you realize you can't use arbitrary XPath expressions here, for example what would you do with a predicate?

  • Count multiple nodes in XML using xPath

    Hi',
    How to count the CUSTSERIAL node in the below XML using xPath.
    <missingICCRec>
    <MissingField xmlns="http://www.Google.com/MissingFields/v1.0">
    <CUSTSERIAL xmlns="http://Google.com/InboundService">23809002RN</CUSTSERIAL>
    <CUSTSERIAL xmlns="http://Google.com/InboundService">23809003RN</CUSTSERIAL>
    <CUSTSERIAL xmlns="http://Google.com/InboundService">23809004RN</CUSTSERIAL>
    </MissingField>
    </missingICCRec>
    Thanks
    Yatan

    Yatan,
    I created a simple BPEL with assign to count the node. Using ora:countNodes() function is throwing exception but when i tried with count() it works.
    XSD seems to be valid. Only you need to have the function as below.
    count(bpws:getVariableData('inputVariable','payload','/client:process/client:missingICCRec/client:MissingField/client:CUSTSERIAL'))
    XSD Used:
    <?xml version="1.0" encoding="UTF-8"?>
    <schema attributeFormDefault="unqualified" elementFormDefault="qualified"
    targetNamespace="http://xmlns.oracle.com/PIMtoRPASAmendment/BPLENodeCount/BPLENodeCount"
    xmlns="http://www.w3.org/2001/XMLSchema">
    <element name="process">
    <complexType>
    <sequence>
    <element name="missingICCRec">
    <complexType>
    <sequence>
    <element name="MissingField">
    <complexType>
    <sequence>
    <element name="CUSTSERIAL" maxOccurs="unbounded" type="string"/>
    </sequence>
    </complexType>
    </element>
    </sequence>
    </complexType>
    </element>
    </sequence>
    </complexType>
    </element>
    <element name="processResponse">
    <complexType>
    <sequence>
    <element name="result" type="string"/>
    </sequence>
    </complexType>
    </element>
    </schema>
    This works !!!
    Please let me know if this helps.
    Thanks,
    Vijay

  • Reading XML using Java

    I want to read all <temp >nodes map them to some variable and create one more XML.
    I am stuck up in the first place itself where i need to read the data :( . I am getting null pointer exception, please find the code also.
    <?xml version="1.0" encoding="UTF-8"?>
    <ftpl id="47" name="XXXXXXXX xxx xxxxxxxx">
    <abc-cab name="Systems" id="43434">
    <abc-dr name="zzzzz" id="4545454">
    <temp key="Type">null</param>
    <temp key="Folder">/ZVZ/XXXXX - xyz</param>
    <temp key="Author">XYZ,ABC</param>
    <temp key="Comments">null</param>
    <temp key="Mailed_By">XYZ,ABC</param>
    <temp key="Subject">null</param>
    <temp key="Key_Words">null</param>
    <abc-page name="1" id="3524012">
    <file text="/asas/asasa/asa/asas/Oxxxxxx2276744.txt" count="1"/>
    </abc-page>
    </abc-dr>
    </abc-cab>
    </ftpl>
    try {
    File file = new File("source-file");
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(file);
    doc.getDocumentElement().normalize();
    System.out.println("Root element " + doc.getDocumentElement().getNodeName());
    NodeList nodeLst = doc.getElementsByTagName("abc-dr");
    for (int s = 0; s < nodeLst.getLength(); s++) {
    Node fstNode = nodeLst.item(s);
    if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
    Element fstElmnt = (Element) fstNode;
    NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("abc-dr");
    Element fstNmElmnt = (Element) fstNmElmntLst.item(1);
    NodeList fstNm = fstNmElmnt.getChildNodes();
    System.out.println("First Node : " + ((Node) fstNm.item(1)).getNodeValue());
    NodeList lstNmElmntLst = fstElmnt.getElementsByTagName("Folder");
    Element lstNmElmnt = (Element) lstNmElmntLst.item(0);
    NodeList lstNm = lstNmElmnt.getChildNodes();
    } catch (Exception e) {
    e.printStackTrace();
    Please help.. let me know the code which read XML I have tried with all SAX/DOM i am getting same NUllPointerExcetion
    Message was edited by:
    JavaNewUser

    Hi
    Thanks patricknz
    pls find the XMl and the java code
    I have again modified the code .. but got the same result as below
    [temp: null]----------------------param =
    [temp: null]----------------------param =
    [temp: null]----------------------param =
    [temp: null]----------------------param =
    [temp: null]----------------------param =
    [temp: null]----------------------param =
    [temp: null]----------------------param =
    [abc-page: null]----------------------abc-page=
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import org.w3c.dom.Document;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    import org.w3c.dom.Element;
    import java.lang.*;
    public class SampleDOM
        public static void main(String s[]){
            try{
                DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
                Document document = docBuilder.parse("C:\\demo.xml");
                   NodeList nodeList = document.getElementsByTagName("abc-dr");
          for (int i = 0, length1 = nodeList.getLength(); i < length1; i++) {
            final Element rDoc = (Element)nodeList.item(i);
            final NodeList rDocC = rDoc.getChildNodes();
            for (int j = 0, length2 = rDocC.getLength(); j < length2; j++) {
              final Node child = rDocC.item(j);
            if (child.getNodeType() == Node.ELEMENT_NODE) {
                Element element = (Element)child;
                System.out.println(element.getChildNodes() + "----------------------" +
                                          new StringBuffer(element.getNodeName()).append(" = "));
            }catch(Exception e){
                e.printStackTrace();
    }XML FIle:-
    <?xml version="1.0" encoding="UTF-8"?>
    <ftpl id="47" name="XXXXXXXX xxx xxxxxxxx">
         <abc-cab name="Systems" id="43434">
              <abc-dr name="zzzzz" id="4545454">
                   <temp key="Type">null</param>
                   <temp key="Folder">/ZVZ/XXXXX - xyz</param>
                   <temp key="Author">XYZ,ABC</param>
                   <temp key="Comments">null</param>
                   <temp key="Mailed_By">XYZ,ABC</param>
                   <temp key="Subject">null</param>
                   <temp key="Key_Words">null</param>
                   <abc-page name="1" id="3524012">
                        <file text="/asas/asasa/asa/asas/Oxxxxxx2276744.txt" count="1"/>
                   </abc-page>
              </abc-dr>
         </abc-cab>
    </ftpl>Message was edited by:
    JavaNewUser
    Message was edited by:
    JavaNewUser

  • Getting error in Mozilla, reading xml using JavaScript

    Hi All,
    I am working with javascript with xml, getting error in Mozilla
    1. see html and xml file and check xml file path before test ---
    2. please, go through the html and xml file.
    read_xml.html
    =================
    <html>
    <head>
    <title>xml file using javascript</title>
    <script type="text/javascript">
    var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
    //loading xml file
    function doLoadXML(xmlFile)
    xmlDoc.async="false";
    xmlDoc.onreadystatechange=doStateVerify;
    xmlDoc.load(xmlFile);
    rootData=xmlDoc.documentElement;
    function doStateVerify()
    if (xmlDoc.readyState != 4)
    return false;
    // reading xml file
    function doReadXML()
    alert("calling function");
    doLoadXML("C:/Documents and Settings/webdeveloper06/Desktop/for_test/comp-info.xml");
    alert("loading file...........");
    var dataArr=new Array();
    dataArr=xmlDoc.getElementsByTagName("comp-info");
    for(var m=0; m <= dataArr.length-1; m++)
              alert("entering inside looping here");
              document.write("<Table border='1px'><tr><td>");     
              document.write(dataArr[m].getElementsByTagName("name")[0].firstChild.nodeValue);
              document.write(dataArr[m].getElementsByTagName("description")[0].firstChild.nodeValue);
              document.write(dataArr[m].getElementsByTagName("web-addr")[0].firstChild.nodeValue);
              document.write(dataArr[m].getElementsByTagName("address")[0].firstChild.nodeValue);
              document.write(dataArr[m].getElementsByTagName("city")[0].firstChild.nodeValue);
              document.write(dataArr[m].getElementsByTagName("postal-code")[0].firstChild.nodeValue);
              document.write(dataArr[m].getElementsByTagName("country")[0].firstChild.nodeValue);
              document.write("</input></td></tr></table>");
    </script>
    </head>
    <body>
    <input type="button" value="Display XML Data" onClick="doReadXML()" />
    </body>
    </html>
    com-info.xml
    =========
    <?xml version="1.0" encoding="iso-8859-1"?>
    <itcopany>
    <comp-info>
    <name>xxx</name>
    <description>IT Reaserch Company</description>
    <web-addr>http://xxx.com</web-addr>
    <address>mehdipatnam</address>
    <city>Hyderabad</city>
    <postal-code>777888888</postal-code>
    <country>IN</country>
    </comp-info>
    <comp-info>
    <name>yyyyy </name>
    <description>Non IT Company</description>
    <web-addr>http://yyyy.com</web-addr>
    <address>xyxxyxyx</address>
    <city>Banglore</city>
    <postal-code>78878787878</postal-code>
    <country>IN</country>
    </comp-info>
    <comp-info>
    <name>zzzzzzz</name>
    <description>IT Company</description>
    <web-addr>http://zzzzzzz.com</web-addr>
    <address>secondrabad</address>
    <city>Hyderabad</city>
    <postal-code>9999999999999</postal-code>
    <country>IN</country>
    </comp-info>
    </itcopany>
    output status
    ============
    1. getting output in IE
    2. not getting output in Mozilla
    Can anyone Helpout, To get data in Mozilla
    regards,
    Abu

    Try to check this document Browser Support for SAP and use PAM (Product Availability Matrix) to check for the compatibility of your SAP system with the browser.
    If you are only the user of the Web Dynpro you would have probably no other choice than change the browser.

  • Read XML using DB Link

    Gurus,
    Is it possible to read/write XML using DB Link?
    If yes please let me know how to achieve this.
    Thanks in Advance.
    Venu

    You need to use quoted names. SQL Server data dictionary stores names in same case they were entered while Oracle in upper case. So when you issue
    Select test.status from testtable@DBLINK test Oracle parser will look for column STATUS while on SQL Server side it could be stored, for examle, as Status or status. Check column names on SQL Server side and use quoted names. Assuming column name is Status:
    Select test."Status" from testtable@DBLINK test SY.

  • Using XPath from Java

    I've heard that you can use XPath from within Java instead of having to use it within XSLT, but I'm not sure what the syntax is?
    Does anyone know?
    Thanks,
    Oodi

    import org.apache.xerces.parsers.DOMParser;
    import org.apache.xpath.XPathAPI;
    DOMParser parser = new DOMParser();
    parser.parse(inputFile);
    doc = parser.getDocument();
    /* Search using XPATH */
    String xpath = "/XpathToSearch";
    NodeIterator nl = XPathAPI.selectNodeIterator(doc, xpath);
    HTH,
    Joe

  • Creating New XML using xPath

    Hi,
    I wanted to know if an XML Document created in the Database using xPaths. I mean, I don't want to creat any XML file on the OS in the first place. I want to create an XML using a table containing xPaths. Can this be done in XDB ?
    Thanks in Advance,
    Piyush

    Hi Piyush
    I don't see how you can create a XML document via xpath!?!? xpath it's only used to reference data in an XML document...
    Chris

  • Creating XML using XPath

    Hello,
    I want to creat XML document using Dom and XPath, as per my knowledge goes I can't create it using XPath {I may b wrong, if I am then pls tell me know :-) }.
    If there doesn't exists any thing like this I am thinkin of wrapping a class {say its XPathProcesserDom} which takes the XPath querry and internaly creates XML Document and returns on request. Is this a good idea :-)
    waiting for comments :-)....
    thanks and regards,
    MaheshPujari

    Hi Piyush
    I don't see how you can create a XML document via xpath!?!? xpath it's only used to reference data in an XML document...
    Chris

  • Upload xml using xpath when data in scattered in different tags

    Hi,
    My problem is "I have to upload a big XML File into a relational master child model of hierarcy=5,but the struture of the xml is not as per the Data Model".I am using the xpath approach in PL/SQL because there is no other way I can get this done.Can you tel me how can I do this effeciently using this approach.Secondly,How can I increase the performance in this scenarion ?
    Thanks a Lot !!!

    Hi Marco,
    Thanks for your advice.
    Please tel me how canI use Xmltype view to come out of this problem.As I already mention that the xml tree is not per the Data model and the nodes name is also differenr so how can I do this.I don't know java but can handle pl/sql.
    Thanks !! Waiting for further advice.

  • Displaying XML using XPath expressions

    Hi. I have a XML file which looks something like this:
    <?xml version="1.0"?>
    <SAQ>
    <question id="1">
    What does UML stand for?
    <answer id="1" correct="yes">
    Unified Modelling Language
    <explanation>
    Explanation
    </explanation>
    </answer>
    <answer id="2" correct="no">
    United Modelling Language
    <explanation>
    Wrong
    </explanation>
    </answer>
    </question>
    I want to just display the Question, not the child Answer and Explantion nodes under it, but when I use:
    <c:set var="temp" value="1" />
    <x:out select="$doc//SAQ//question[@id = $temp]" />
    it displays:
    What does UML stand for? Unified Modelling Language Explanation United Modelling Language Wrong
    How do I just display the parent question node and not its child answer and explanation nodes?
    Thanks!

    use the text() xpath function it should work:
    <x:out select="$doc//SAQ//question[@id = $temp]/text()" />

  • Reading XML using JSP

    Hi,
    My company just bought a software, which this s/w will generate a HTML file with the XML tags and data inside it.
    I will need to read the XML tags and data inside the HTML file using JSP.
    Does anyone know how to do this?
    Please help mi!!Thanks!

    http://java.sun.com/webservices/docs/1.1/tutorial/doc/index.html

  • How to retrieve a node using xpath in java

    Hi,
    I need to make an application in which on click of a button an xml is
    displayed on the browser.
    Now when a user selects a node in the xml then i need the xpath of the selected node for some processing.
    How to retrieve the xpath.
    I am using Struts framework.

    There is not a specific method for achieving this.
    You can store the whole xml document into a defined
    structure. And get the needed xpath by some index.Yes i know that i'll need to store the file.
    But my XML is fixed and the same XML is used everytime.
    Now the structure of the XML is like it has same named nodes inside the parent node.
    example :
    <Human>
    <Person>
    <Person></Person>
    <Person>
    <Person><name>fsfsdsdf</name></Person>
    </Person>
    </Person>
    <Human>
    Now if the user selects the person node which contains name node then how to get the XPATH.
    Can u help regarding the same........

  • Need help with reading XML using File Adapter

    I have created a simple BPEL process that uses a file adapter to read files containing XML messages of a simple xsd schema. But when reading the xml, I get the following error message:
    [2010/03/01 23:43:13] Invalid data: The value for variable "Receive_1_Read_InputVariable", part "revision-report" does not match the schema definition for this part.The invalid xml document is shown below: More...
    [2010/03/01 23:43:13] "{http://schemas.oracle.com/bpel/extension}invalidVariables" has been thrown. less
    -<invalidVariables xmlns="http://schemas.oracle.com/bpel/extension">
    -<part name="code">
    <code>
    9710
    </code>
    </part>
    -<part name="summary">
    <summary>
    Invalid xml document.
    According to the xml schemas, the xml document is invalid. The reason is: Error::cvc-complex-type.4: Attribute 'doc' must appear on element 'revision-report'.
    Error::cvc-complex-type.4: Attribute 'model' must appear on element 'revision-report'.
    Error::cvc-complex-type.4: Attribute 'pubdate' must appear on element 'revision-report'.
    Error::cvc-complex-type.2.4.b: The content of element 'revision-report' is not complete. One of '{"http://xmlns.oracle.com/xmlfile":alternategroup}' is expected.
    Please make sure that the xml document is valid against your schemas.
    </summary>
    </part>
    </invalidVariables>
    It seems that there is some issue with the namespace, but even after trying out various combinations, I am not able to resolve this.
    Here the message schema (xsd):
    <?xml version="1.0" encoding="UTF-8" ?>
    <xs:schema elementFormDefault="qualified"
    targetNamespace="http://xmlns.oracle.com/xmlfile"
    xmlns:tns="http://xmlns.oracle.com/xmlfile"
    xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="revision-report">
    <xs:complexType>
    <xs:sequence maxOccurs="unbounded">
    <xs:element name="alternategroup">
    <xs:complexType>
    <xs:attribute name="name" use="required" type="xs:string"/>
    <xs:attribute name="Desc" use="required" type="xs:string"/>
    </xs:complexType>
    </xs:element>
    </xs:sequence>
    <xs:attribute name="doc" use="required" type="xs:string"/>
    <xs:attribute name="model" use="required" type="xs:string"/>
    <xs:attribute name="pubdate" use="required" type="xs:string"/>
    </xs:complexType>
    </xs:element>
    </xs:schema>
    And here is the xml file to be read by the file adapter:
    <?xml version="1.0" encoding="UTF-8" ?>
    <revision-report doc="doc2" model="model4" pubdate="pubdate5">
    <alternategroup Name="ABC" Desc="ABC-Desc">
    </alternategroup>
    <alternategroup Name="DEF" Desc="DEF-Desc">
    </alternategroup>
    <alternategroup Name="GHI" Desc="GHI-Desc">
    </alternategroup>
    </revision-report>
    Appreciate any help.
    Thanks in advance for your attention.
    Jay

    Thanks for your response.
    I am not sure if there is any easier way, but I tried out the following tool available on the net to check an xml against a xsd:
    http://tools.decisionsoft.com/schemaValidate/
    There were a few issues, that I corrected and finally had a xsd and xml that were matching and valid. I tried this out in my file reading BPEL process, but the error still remained the same!
    Here is my updated/simplified xsd and xml:
    <?xml version="1.0" encoding="UTF-8" ?>
    <xs:schema targetNamespace="http://xmlns.oracle.com/xmlfile"
    xmlns:tns="http://xmlns.oracle.com/xmlfile"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns="http://xmlns.oracle.com/xmlfile">
    <xs:element name="revision-report">
    <xs:complexType>
    <xs:sequence>
    <xs:element maxOccurs="unbounded" ref="alternategroup"/>
    </xs:sequence>
    <xs:attribute name="doc" use="required" type="xs:string"/>
    <xs:attribute name="model" use="required" type="xs:string"/>
    <xs:attribute name="pubdate" use="required" type="xs:string"/>
    </xs:complexType>
    </xs:element>
    <xs:element name="alternategroup">
    <xs:complexType>
    <xs:attribute name="Name" use="required" type="xs:string"/>
    <xs:attribute name="Desc" use="required" type="xs:string"/>
    </xs:complexType>
    </xs:element>
    </xs:schema>
    <?xml version="1.0" encoding="UTF-8" ?>
    <revision-report doc="doc2" model="model4" pubdate="pubdate5" xmlns="http://xmlns.oracle.com/xmlfile">
    <alternategroup Name="ABC" Desc="ABC-Desc"/>
    <alternategroup Name="DEF" Desc="DEF-Desc"/>
    <alternategroup Name="GHI" Desc="GHI-Desc"/>
    </revision-report>
    I even tried the option that is available in JDeveloper to generate a sample xml from a xsd (when in the context of a Transformation activity). The xml generated by this also seems exactly like the one above.
    So, I am not able to figure out why my BPEL process errors out with the message Invalid xml document.

  • How to remove elements/attributes from XML using Xpath in XSLT ??

    Hello ,
    Is there anyway or method of Xpath from which I can delete the elements and attributes from XML at runtime ??
    Like I have such XML and I have to remove per attribute highlighted below
    <person per="and">
    <e:emp a="ir" b="ad" >
    </e:emp>
    </person>
    And want a result like this
    <person>
    <e:emp a="ir" b="ad" >
    </e:emp>
    </person>
    Thanks

    To achieve this you can use the bpelx:remove function: http://download.oracle.com/docs/cd/E12483_01/integrate.1013/b28981/manipdoc.htm#CIHJBJFD
    your assign will look like:
    <bpel:assign>
    <bpelx:remove>
    <target variable="person" query="/person/@per" />
    </bpelx:remove>
    </bpel:assign>
    Regards,
    Melvin

Maybe you are looking for

  • Coldfusion 11 java/jre ssl mutual auth api calls.  Help with coldfusion/java logs.

    Hello, I am here because I have exhausted my Coldfusion/Java ssl keystore certs trouble shooting abilities.  Here is the issue. I am developing a Coldfusion 11 application that must make api calls to Chase payconnexion SOAP services. I am using the c

  • Problem while using reply all with non english sen...

    My company recently decided to also inlcude the chinese name in the e-mail address. When the directory is updated, I face some difficulities when replying mail. There are some e-mail addresses are not recognized properly and resulted in Nokia Mail fo

  • Xperia Z3v Head Phone Jack Cover

    Just curious if any one of you had dipped your Xperia Z3v in water....On sonymobile.com it says that make sure all the ports are closed, but the phone did not come with a head phone jack cover.  Does that mean it is already waterproof?  I examined al

  • Passing variables from DM to logic script problem (REPLACEPARAM)

    Dear All, I would like to send variables from data manager to a logic script. The script copies values from an account to an other. If I hardcode two accounts in the script, it works fine, but I want to pass these two accounts dynamically from data m

  • InterApplication Navigation in java webdynpro

    Hi Gurus , Please guide me for the following scenario : -   I have developed an application for InterApplication Navigation  i.e one Webdynpro Projcet containing multiple application. My project contained two applications and defined one parameter to