Need examples of code to parse the xml using kxml2

Hello world

I am a beginner for Blackberry, I want to get the data from the xml file. I look and see the section use of kxml2 is a better choice.

But I can't find an example code for it on the Blackberry.  Can someone share me?

I open kxml2.jar, I see xmlParser and kxmlParser, whoever I'm use()?

Anbody can help me contact how to use kxml2 clearly?

Thank you very much. Sorry for the bad English.

--------

Binh - VietNam

Ah yes, sorry, I assumed automatically kxml to be used with ksoap2.

kxml is a j2me parser commonly you can find sources in other forums, for example
http://www.developer.Nokia.com/community/wiki/How_to_parse_an_XML_file_in_Java_ME_with_kXML
http://j2mesamples.blogspot.com/2009/04/XML-parsing-in-J2ME.html

Tags: BlackBerry Developers

Similar Questions

  • How to parse the XML from the server BB10 Cascades development

    Hi all

    I'm new to BB10 development.

    I made the connection with my server that sends data to the XML Format. How to analyze.  Can someone help me with this.

    Also how to store data analysed in the Global Variable or ArrayList.

    Concerning

    Stephenson

    I thought you wanted to do stunts (qml).
    I use Qt

    QByteArray data = currentReply->readAll();
    xml.addData(data); //xml is a QXmlStreamReader
    

    to parse the xml, it is pretty simple if you look at the API.

    Here is a snippet of my code:

    while (!xml.atEnd()) {
        xml.readNext();
        /** start of an element **/
        if (xml.isStartElement()) {
            currentTag = xml.name().toString();
            if (xml.name() == "version") {
    

    the feed reader goes hierarchically, so you can simply call routines to analyze the different parts of the xml if the name() corresponds to a certain value.

  • having a problem with parsing the XML file

    Hi all
    I am trying to get data from XML file
    I want to only 4-5 values in this XML file
    Here is an example of XML file
    -< transaction >
    -< TransCtx >
    > < pAMETranType > IRCVACAPPROVAL < / pAMETranType >
    > < / TransCtx >
    > < / transaction >

    I want to add value and to store this value in table
    I'm here, I want to "IRCVACAPPROVAL".
    the tag
    < pAMETranType >

    for this purpose


    I created a procedure

    CREATE OR REPLACE PROCEDURE insert_xml_emps (p_directory in varchar2,
    > p_filename in varchar2)
    (> vtableName in varchar2) as
    > v_filelocator BFILE.
    > v_cloblocator CLOB.
    > l_ctx DBMS_XMLSTORE. CTXTYPE;
    > l_rows NUMBER;
    > v_amount_to_load NUMBER;
    > dest_offset NUMBER: = 1;
    > offset NUMBER: = 1;
    > lang_context NUMBER: = DBMS_LOB. DEFAULT_LANG_CTX;
    > WARNING NUMBER;
    > START
    > dbms_lob.createtemporary (v_cloblocator, true);
    > v_filelocator: = bfilename (p_directory, p_filename);
    > dbms_lob.open (v_filelocator, dbms_lob.file_readonly);
    > v_amount_to_load: = DBMS_LOB.getlength (v_filelocator);
    >-* this line is changed * -.
    > DBMS_LOB. LOADCLOBFROMFILE (v_cloblocator,
    > v_filelocator.
    > v_amount_to_load.
    > dest_offset.
    > offset.
    > 0,
    > lang_context.
    (> warning);
    >
    > l_ctx: = DBMS_XMLSTORE.newContext (vTableName);
    > DBMS_XMLSTORE.setRowTag (l_ctx, 'TRANSACTION');
    > DBMS_XMLSTORE.setRowTag (l_ctx, 'TRANSCTX');
    >-clear the update settings
    > DBMS_XMLStore.clearUpdateColumnList (l_ctx);
    >-set the columns to update a list of values
    > DBMS_XMLStore.setUpdateColumn (l_ctx, 'PAMETRANTYPE');
    >
    >-now insert the doc.
    > l_rows: = DBMS_XMLSTORE.insertxml (l_ctx, v_cloblocator);
    > DBMS_XMLSTORE.closeContext (l_ctx);
    > dbms_output.put_line(l_rows ||) "... inserted rows. ») ;
    > dbms_lob.close (v_filelocator);
    > DBMS_LOB. FREETEMPORARY (v_cloblocator);
    > END;

    I also have on the table who get this value

    whenever I call that created the procedure
    it sometime gives an error or sometime run correctly but store null in the table


    But when I change the XML file
    as
    When convert all lowercase letters in the capital then it works fine

    Is tehre to other ways to parse the XML file with no change in the XML file?

    Did you use the same test (with the exception of file name and directory) case?

    What I posted is a copy/paste direct SQL * Plus, and it works on version 11.2.0.1.

  • Hello, I need help, I can't play the video using Facebook. Works very well in Youtube. I use Safari. Tried different solutions such as changing preferences, reinstalling Flash.

    Hello, I need help, I can't play the video using Facebook. Works very well in Youtube. I use Safari. Tried different solutions such as changing preferences, reinstalling Flash.

    Hello

    Please try following the steps and see if it helps

    1. Please work through this guide.

    https://helpx.Adobe.com/Flash-Player/KB/video-playback-issues.html

    Follow the instructions in the guide on the provision of the dxdiag report and additional information on what you tested and observed.

    2 turn off hardware acceleration in the settings. Steps are mentioned in the link below

    How to disable or enable hardware acceleration?

    Thank you

  • Need help to parse the xml string to populate the drop-down list

    Here is my: problem

    I have a hidden text field that contains the text of an xml

    <>facilities
    < building >
    < name > Building A < / name >
    < name > building B < / name >
    < name > building C < / name >
    < name > building D < / name >
    < name > building E < / name >
    < name > building F < / name >
    < name > building G < / name >
    < name > building H < / name >
    < / build >
    < / facilities >

    My goal is to read this with JavaScript xml string to populate a drop-down list with values of element (name). Does anyone know how script that?

    Attached is a sample .xdp

    See you soon,.

    Jesse

    Here is an example of change. I put the code click on the button, so you can see it in operation... You can place this code in the event that makes sense for you. I also added another field to show the DOM (this is for debugging purposes and you can remove this field if you want).

    Paul

  • How can I parse the XML file using the Oracle's Sql query.

    Hi all
    I have an XML file that must analyze and display the result according to the following example
    Can you please recommend me an approach to get the result.

    For example, here is my XML:

    <? XML version = "1.0" encoding = "UTF-8"? >
    < xmlns:pi = "urn:com.workday / picof pi: Extract_Employees" >
    < IP: employee >
    < Additional_Information: pi > < pi: pi function: PriorValue = "" > Intern - masteri¿½s < / pi: function >
    < / pi: Additional_Information >
    < / pi: employee >
    < / pi: Extract_Employees >

    Databases:

    Oracle Database 10 g Enterprise Edition release 10.2.0.3.0 - production

    SQL > SELECT * FROM NLS_DATABASE_PARAMETERS;

    NLS_LANGUAGE AMERICAN
    NLS_TERRITORY AMERICA
    NLS_CURRENCY $
    NLS_ISO_CURRENCY AMERICA
    NLS_NUMERIC_CHARACTERS.,.
    WE8ISO8859P1 NLS_CHARACTERSET
    NLS_CALENDAR GREGORIAN
    NLS_DATE_FORMAT DD-MON-RR
    NLS_DATE_LANGUAGE AMERICAN
    NLS_SORT BINARY
    NLS_TIME_FORMAT HH.MI. SSXFF AM
    NLS_TIMESTAMP_FORMAT-DD-MON-RR HH.MI. SSXFF AM
    NLS_TIME_TZ_FORMAT HH.MI. SSXFF AM TZR
    NLS_TIMESTAMP_TZ_FORMAT DD-MON-RR HH.MI. SSXFF AM TZR
    NLS_DUAL_CURRENCY $
    BINARY NLS_COMP
    NLS_LENGTH_SEMANTICS BYTES
    NLS_NCHAR_CONV_EXCP FAKE
    NLS_NCHAR_CHARACTERSET AL16UTF16
    NLS_RDBMS_VERSION 10.2.0.3.0



    The Xml file above with UTF-8 character sets which is multi bytes.

    But in my character database is WE8ISO8859P1 for example ISO-8859-1 (single-byte character set)

    SQL > SELECT extractValue (Value (x) ', ' / pi:Employee/pi:Additional_Information/pi:Job_Title','xmlns:pi="urn:com.workday/picof ' ')
    TABLE (XMLSequence (extract (XMLType (bfilename('XMLDIR','XML_Issue_227176.xml'), nls_charset_id ('AL32UTF8')),'/ pi: Employee ',' xmlns:pi="urn:com.workday/picof"'))) x;)))


    which gives the following error:

    Error:
    ORA-31011: XML parsing failed
    ORA-19202: an error has occurred in the processing of XML
    LPX-00200: could not convert from UTF-8 encoding to ISO-8859-1
    Error on line 1
    ORA-06512: at "SYS." XMLTYPE", line 295
    ORA-06512: at line 1

    Also I tried with this
    SQL > SELECT convert (extractValue (Value (x), ' / pi:Employee/pi:Additional_Information/pi:Job_Title','xmlns:pi="urn:com.workday/picof"'),'WE8ISO8859P1 ', 'UTF8'))
    TABLE (XMLSequence (extract (XMLType (bfilename('XMLDIR','XML_Issue_227176.xml'), nls_charset_id ('AL32UTF8')),'/ pi: Employee ',' xmlns:pi="urn:com.workday/picof"'))) x;)))

    The same error is according to the above error message.

    Please help in this regard.

    Thank you and best regards,
    Sandrine

    You know the code of real character behind "" or you receive the file like that?

    For the record, "" is the wildcard of UTF-8 (0xEFBFBD), so that the original character of the means has already been replaced and that very probably the file was not coded properly in the first place.

    With respect to the resolution of the problem, try another method to read the file:

    SQL> select value from nls_database_parameters where parameter = 'NLS_CHARACTERSET';
    
    VALUE
    ----------------------------------------
    WE8ISO8859P15
    
    SQL> SELECT x.*
      2  FROM XMLTable(
      3         XMLNamespaces(default 'urn:com.workday/picof')
      4       , '/Extract_Employees/Employee'
      5         passing xmltype(
      6                   dbms_xslprocessor.read2clob(
      7                     'COP_DIR'
      8                   , 'XML_Issue_227176.xml'
      9                   , nls_charset_id('AL32UTF8')
     10                   )
     11                 )
     12         columns job_title varchar2(30) path 'Additional_Information/Job_Title'
     13       ) x
     14  ;
    
    JOB_TITLE
    ------------------------------
    Intern -  Master¿s
     
    
  • Parse the XML file and extract data

    I want to parse a XML file and get the data as columns.

    Input country.xml file:

    <?xml version="1.0" encoding="UTF-8"?>
    <MAS Action="Insert">
    <Country ObjectId="100000000000000009" VersionId="8"><Id>1</Id><NlTexts><Name Language="de">Land1</Name><Name Language="en">Country1</Name></NlTexts></Country>
    <Country ObjectId="100000000000000033" VersionId="2"><Id>2</Id><NlTexts><Name Language="de">Land2</Name><Name Language="en">Country1</Name></NlTexts></Country>
    </MAS>
    
    

    I would like to analyze the xmlfile to get the following result

    Required result:

    col1        col2           col3
    1            Land1        Country1
    2            Land2        Country2
    

    or alternatively

    col1  col2       
    1            Land1       
    1            Country1
    2            Land2       
    2            Country2
    

    I tried the extract function

    select extract((XMLTYPE(BFILENAME('XML_DAT_DIR', 'country.xml'),
               NLS_CHARSET_ID('AL32UTF8'))) , '/*/*/Id') as "xdata"
    from dual;
    
    xdata
    ------------------------
    <Id>1</Id><Id>2</Id>
    

    and XMLTABLE (but how can I add countries now)

    SELECT *
        FROM XMLTABLE('/*/*/Id'
               PASSING XMLTYPE(BFILENAME('XML_DAT_DIR', 'country.xml'),
               NLS_CHARSET_ID('AL32UTF8'))
           )
      ;
    COLUMN_VALUE
    ------------------------
    <Id>1</Id>
    <Id>2</Id>
    

    DB version 11.2.0.3 on Windows 64-bit

    Thank you

    Tim

    Here are a few examples.

    For your output required:

    SELECT *.

    FROM XMLTable)

    "/ MAS/country".

    from XMLType (bfilename ('TEST_DIR', 'country.xml'), nls_charset_id ('AL32UTF8'))

    number of columns col1 way "Id".

    , col2 varchar2 (30) path "NlTexts/name [1].

    , col3 varchar2 (30) path "NlTexts/name [2]»

    )

    ;

    or, if the Language attribute is significant:

    SELECT *.

    FROM XMLTable)

    "/ MAS/country".

    from XMLType (bfilename ('TEST_DIR', 'country.xml'), nls_charset_id ('AL32UTF8'))

    number of columns col1 way "Id".

    col2 varchar2 (30) path "NlTexts/Name[@Language="de"]"

    col3 varchar2 (30) path "NlTexts/Name[@Language="en"]"

    )

    ;

    For your alternate exit:

    SELECT x1.col1

    x2.col2

    -, x2.col3

    FROM XMLTable)

    "/ MAS/country".

    from XMLType (bfilename ('TEST_DIR', 'country.xml'), nls_charset_id ('AL32UTF8'))

    number of columns col1 way "Id".

    , path of xmltype names ' NlTexts/name '.

    ) x 1

    XMLTable)

    "/ Name".

    in passing x1.names

    path of column col2 varchar2 (30) '.'

    -, col3 to ordinalite

    ) x 2

    ;

    (uncomment col3 to see what he does)

    or in a shorter way:

    SELECT *.

    FROM XMLTable)

    ' for $i/MAS/country

    , $j in $ NlTexts/i/name

    Returns the r element {$i / Id, $j}'

    from XMLType (bfilename ('TEST_DIR', 'country.xml'), nls_charset_id ('AL32UTF8'))

    number of columns col1 way "Id".

    , col2 varchar2 (30) path 'name '.

    ) ;

  • Inability to parse the XML file

    Podcasts connect tells me that it cannot parse the following URL.  You can determine why?  The URL http://www.nudge.online/Protest/Podcasts/hungerstriker.xml

    I followed, as far as possible, the advice provided by PodcastConnect

    Line 18 of your food

    < height > 144 < / height >

    The misspelling has given rise to the 'height' never closed and thus invalidate the rest of the food.

  • Examples of code to create the connection of BWS

    Hi I started using BWS (Blackberry Web Services) recently after the use of BAA (Blackberry Administration API) for some time. I would get a tutorial or sample code showing the initialization of the connection to the BWS and then use it to call the getUsersDetail method. I have the below code is missing the connection of BWS.

    import java.util.List;
    
    import com.rim.ws.enterprise.admin.*;
    public class BWSTest {
    
        public static String locale = "en_US";
        public static void main(String[] args){
    
            RequestMetadata requestMetadata = new RequestMetadata();
            requestMetadata.setLocale(locale);
            GetUsersDetailRequest userRequest = new GetUsersDetailRequest();
            userRequest.setMetadata(requestMetadata);
            userRequest.setLoadDevices(true);
            userRequest.setLoadAccounts(true);
            userRequest.setLoadITPolicies(true);
            userRequest.setLoadSWConfigs(true);
    //      List allUsers=userRequest.getUsers(); this method reflects users added as part of the request, not resulting from it
            GetUsersDetailResponse response = bws.getUsersDetail(request);
    
            if (response.getReturnStatus().getCode().compareTo("SUCCESS") !=0){
                System.out.println("Error occurred: "+response.getReturnStatus().getMessage() );
            }
    
            for(GetUsersDetailIndividualResponse individualResponse:response.getIndividualResponses()){
                individualResponse.getUserDetail().getDisplayName();
            }
    
        }
    
    }
    

    I found this code on the following link in a zip file:

    BWS Java sample

    import java.net.MalformedURLException;
    import java.net.URL;
    
    import javax.xml.ws.BindingProvider;
    
    import com.rim.ws.enterprise.admin.BWS;
    import com.rim.ws.enterprise.admin.BWSService;
    import com.rim.ws.enterprise.admin.BWSUtil;
    import com.rim.ws.enterprise.admin.BWSUtilService;
    import com.rim.ws.enterprise.admin.GetEncodedUsernameRequest;
    import com.rim.ws.enterprise.admin.GetEncodedUsernameResponse;
    import com.rim.ws.enterprise.admin.GetUsersRequest;
    import com.rim.ws.enterprise.admin.GetUsersResponse;
    import com.rim.ws.enterprise.admin.GetUsersSearchCriteria;
    import com.rim.ws.enterprise.admin.GetUsersSortBy;
    import com.rim.ws.enterprise.admin.RequestMetadata;
    import com.rim.ws.enterprise.admin.User;
    
    /**
     * This simple program finds users on the BlackBerry Administration Server,
     * and displays the existing users in the Console output.
     *
     * @author gbeukeboom
     *
     */
    
    public class TestMain {
    
        public static BWSService _myBWSService;
        public static BWS _bws;
        public static BWSUtilService _myBWSUtilService;
        public static BWSUtil _bwsUtil;
        private static String _locale = "en_US";
        private static String _clientVersion = "5.0.3"; //The version of BAS this application was created for
        private static RequestMetadata _meta = new RequestMetadata();;
    
        private static boolean setup() {
            String strBASURL=System.getProperty("basurl");
            URL serviceUrl = null;
            URL utilServiceUrl=null;
    
            //The Metadata object includes information about this application, it is included with every call
            _meta.setClientVersion(_clientVersion);
            _meta.setOrganizationUid("0"); //Not used currently, set to "0"
            _meta.setLocale(_locale);
    
            try {
                serviceUrl = new URL("https://" + strBASURL + "/enterprise/admin/ws?wsdl");
                utilServiceUrl = new URL("https://" + strBASURL + "/enterprise/admin/util/ws?wsdl");
            } catch (MalformedURLException e) {
                System.err.println("Cannot initialize the wsdl");
                return false;
            }
    
            //Initialize our web service stubs that will be used for all calls
            _myBWSService = new BWSService(serviceUrl);
            _bws = _myBWSService.getBWS();
            _myBWSUtilService = new BWSUtilService(utilServiceUrl);
            _bwsUtil = _myBWSUtilService.getBWSUtil();
    
            String username=System.getProperty("username");
            String password=System.getProperty("password");
    
            GetEncodedUsernameRequest request=new GetEncodedUsernameRequest();
            request.setMetadata(_meta);
            request.setUsername(username);
            request.setDomain(strBASURL);
    
            //The BAS expects the username to be encoded, this call returns the encoded value
            GetEncodedUsernameResponse geurResponse = _bwsUtil.getEncodedUsername(request);
    
            if (geurResponse.getReturnStatus().getCode().compareTo("SUCCESS") != 0){
                System.out.println("Error occurred: " + geurResponse.getReturnStatus().getMessage());
                return false;
            }
    
            String myEncodeUsername = geurResponse.getEncodedUsername();
    
            //Set http basic authentication on the web service
            BindingProvider bp = (BindingProvider)_bws;
            bp.getRequestContext().put(BindingProvider.USERNAME_PROPERTY, myEncodeUsername);
            bp.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, password);
    
            return true;
        }
    
        public static void getUsers() {
    
            GetUsersRequest request = new GetUsersRequest();
            request.setMetadata(_meta); //Assign our Metadata to the call
    
            //This criteria object could be used to specify search parameters
            GetUsersSearchCriteria searchCriteria = new GetUsersSearchCriteria();
    
            request.setSearchCriteria(searchCriteria);
            request.setPageSize(500);
    
            GetUsersSortBy sortBy = new GetUsersSortBy();
            sortBy.setEMAILADDRESS(true);
            sortBy.setValue("EMAIL_ADDRESS");
            request.setSortBy(sortBy);
            request.setSortAscending(true);
    
            GetUsersResponse response = _bws.getUsers(request);
    
            //If the result returned from the call is SUCCESS then we loop through all returned users
            //outputting their information to the console.
            if (response.getReturnStatus().getCode().compareTo("SUCCESS") != 0){
                System.out.println("Error occurred: " + response.getReturnStatus().getMessage());
            } else if (response.getUsers() != null) {
                for (User itr: response.getUsers()) {
                    System.out.println("Display name: " + itr.getDisplayName());
                    System.out.println("User ID: " + itr.getUid());
                    for (String emailAddress :itr.getEmailAddresses() ){
                        System.out.println("Email Address: " + emailAddress);
                    }
                    System.out.print("\n");
                }
            }
        }
    
        /**
         * @param args
         */
        public static void main(String[] args) {
            System.out.println("Starting to intiialize credentials...");
            if (!setup()){
                System.out.println("Problem occurred while setting up credentials.");
                System.exit(0);
            }
            System.out.println("Credentials initialized.\n");
            System.out.println("Starting to retrieve users...");
            getUsers();
        }
    
    }
    
  • Unable to parse the XML because of malformed UTF-8

    When parsing a string xml (not a file!) I have a malfromed exception UTF-8. This is due to the fact that there are accents in (oau), but the chain says it utf-8 format. These umlauts or even some Chinese characters are allowed by the xml specification.

    You have an idea on how to make this work? the problem is that I can't just replace the characters with something else since I have to support any language.

    Sring xml ="" my name: oauRed535.

    DocumentBuilderFactory plant = DocumentBuilderFactory.newInstance ();

    DocumentBuilder builder = factory.newDocumentBuilder ();

    InputStream inputStream = new ByteArrayInputStream (xml.getBytes ());

    Document document = builder.parse (inputStream);

    Exception message when you call parse: Malformed UTF-8

    Any help welcome,

    Thank you

    Is the point of this item:

    my name: oau

    to test the transformation of accented characters?

    In any case, I'll try:

    xml.getBytes("UTF-8")

    to make sure that your string is encoded using UTF-8 and not ISO-8859-1 which is the default.

  • Help in parsing the XML result with ksoap2

    Hi, I have another problem. I used KSOAP2 to call a web service net but when I catch him to display the result with a selectionneret, it shows the following screen:

    reading on the web, I didn't find a good way to analyze the result. Could you help me with this? Thanks in advance

    Thanks, the problem here is that we use the same webservice for more devices and a web page in .NET) that's why we use this webservice. Anyway thanks for the help. I read a lot of posts and the only way is perhaps to save the XML document in the SD card

  • Need of Javascript code to change the color of the text field

    Looking for a code Javascript change the background of textfield color and outline color in acrobat?  (without any reference to xfa)

    The background color is the field fillColor property: http://livedocs.adobe.com/acrobat_sdk/9.1/Acrobat9_1_HTMLHelp/JS_API_AcroJS.88.705.html

    and the outline color is the property of strokeColor: http://livedocs.adobe.com/acrobat_sdk/9.1/Acrobat9_1_HTMLHelp/JS_API_AcroJS.88.723.html

  • Add a xmlns tag to the XML using DBMS_XMLGEN

    I'm using the version of Oracle version 10.1.0.4.2.

    I want to create an xml file according to some data in the relational database tables. For the same thing, I created object types and discovers with the types of objects, since the data is divided into several tables.

    Then, I used DBMS_XMLGEN.getxml to generate xml with queries from the view of the object.

    Y at - it an option to add the xmlns attribute in the xml file generated.

    Please let me know if any additional details are needed.

    If you want to add the namespace declaration to the root element, I don't think it's possible with DBMS_XMLGEN directly.
    You can ask DBMS_XMLGEN to treat some of the fields of the object as XML attributes by prefixing with '@' (for example '@my_attribute'), but you can't control which for bounding of the elements.

    A possible solution is to add it later, using XSLT, or insertChildXML, but apparently it is not available in your version.

    However...

    For the same thing, I created object types and discovers with the types of objects, since the data is divided into several tables.

    Because the data from different tables, why not use SQL and SQL/XML functions to build the document?
    This is simple, simple and needs no additional items.

    select xmlelement("Departments",
             xmlattributes('http://xmlns.example.org' as "xmlns")
           , xmlagg(
               xmlelement("Department",
                 xmlattributes(d.deptno as "Id")
               , xmlelement("Name", d.dname)
               , xmlelement("Employees"
                 , xmlagg(
                     xmlelement("Employee",
                       xmlattributes(e.empno as "Id")
                     , xmlforest(
                         e.ename as "Name"
                       , e.job as "Job"
                       )
                     ) order by e.empno
                   )
                 )
               ) order by d.deptno
             )
           )
    from scott.dept d
         join scott.emp e on e.deptno = d.deptno
    group by d.deptno, d.dname
    ;
    

    Output:

    
      
        ACCOUNTING
        
          
            CLARK
            MANAGER
          
          
            KING
            PRESIDENT
          
          
            MILLER
            CLERK
          
        
      
      
        RESEARCH
        
          
            SMITH
            CLERK
          
          
            JONES
            MANAGER
          
          
            FORD
            ANALYST
          
        
      
      
        SALES
        
          
            ALLEN
            SALESMAN
          
          
            WARD
            SALESMAN
          
          
            MARTIN
            SALESMAN
          
          
            BLAKE
            MANAGER
          
          
            TURNER
            SALESMAN
          
          
            JAMES
            CLERK
          
        
      
    
    
  • How can I recursively parse an xml using XQuery document?

    I have an open and I have to using XQuery in Response.xml can transform someone give me an idea how to analyze recursive Xml using XQuery documents. Any help will be appreciated. Thanks in advance

    Open

    " < = xmlns:ns0 ns0:GlobalRoutePlanServiceGOPResponse ' http://www.example.org/input ">

    < GlobalRoutePlanServiceResponse >

    < response >

    Buid_1 < Buid > < / Buid >

    SalesOrderId_1 < SalesOrderId > < / SalesOrderId >

    EODD_1 < EODD > < / EODD >

    LODD_1 < LODD > < / LODD >

    < legs >

    < leg >

    < level > 1 < / level >

    < Resources > ShipMode_1 < / resources >

    < FSBD > FSBD_1 < / FSBD >

    FABD_1 < FABD > < / FABD >

    < leg >

    < leg >

    < niv.2 > < / level >

    < Resources > ShipMode_2 < / resources >

    < FSBD > FSBD_1 < / FSBD >

    FABD_1 < FABD > < / FABD >

    < leg >

    < leg >

    < level > 3.1 < / level >

    < resources > ShipMode_3.1 & amp; < / resources >

    < FSBD > FSBD_1 < / FSBD >

    FABD_1 < FABD > < / FABD >

    < leg >

    < leg >

    < level > 4.1 < / level >

    < Resources > ShipMode_4.1 < / resources >

    < FSBD > FSBD_1 < / FSBD >

    FABD_1 < FABD > < / FABD >

    < leg > < / foot >

    < / foot >

    < / foot >

    < / foot >

    < leg >

    < level > 3.2 < / level >

    < Resources > ShipMode_3.2 < / resources >

    < FSBD > FSBD_1 < / FSBD >

    FABD_1 < FABD > < / FABD >

    < leg >

    < leg >

    < level > 4.2 < / level >

    < Resources > ShipMode_4.2 < / resources >

    < FSBD > FSBD_1 < / FSBD >

    FABD_1 < FABD > < / FABD >

    < leg > < / foot >

    < / foot >

    < / foot >

    < / foot >

    < / foot >

    < / foot >

    < / foot >

    < / foot >

    < / legs >

    < / answer >

    < / GlobalRoutePlanServiceResponse >

    < / ns0:GlobalRoutePlanServiceGOPResponse >

    Response.Xml

    " < = xmlns:ns0 ns0:InputParameters ' http://xmlns.Oracle.com/pcbpel/adapter/DB/SP/GOP_DB_FSL_Msg_Persist_SVC "> "

    < ns0:P_LEG >

    < ns0:P_LEG_ITEM >

    < ns0:LEGS_LEVEL > 1 < / ns0:LEGS_LEVEL >

    < ns0:SHIPMODE > ShipMode_1 < / ns0:SHIPMODE >

    < / ns0:P_LEG_ITEM >

    < ns0:P_LEG_ITEM >

    < ns0:LEGS_LEVEL > 2 < / ns0:LEGS_LEVEL >

    < ns0:SHIPMODE > ShipMode_2 < / ns0:SHIPMODE >

    < / ns0:P_LEG_ITEM >

    < ns0:P_LEG_ITEM >

    < ns0:LEGS_LEVEL > 3.1 < / ns0:LEGS_LEVEL >

    < ns0:SHIPMODE > ShipMode_3.1 < / ns0:SHIPMODE >

    < / ns0:P_LEG_ITEM >

    < ns0:P_LEG_ITEM >

    < ns0:LEGS_LEVEL > 4.1 < / ns0:LEGS_LEVEL >

    < ns0:SHIPMODE > ShipMode_4.1 < / ns0:SHIPMODE >

    < / ns0:P_LEG_ITEM >

    < ns0:P_LEG_ITEM >

    < ns0:LEGS_LEVEL > 3.2 < / ns0:LEGS_LEVEL >

    < ns0:SHIPMODE > ShipMode_3.2 < / ns0:SHIPMODE >

    < / ns0:P_LEG_ITEM >

    < ns0:P_LEG_ITEM >

    < ns0:LEGS_LEVEL > 4.2 < / ns0:LEGS_LEVEL >

    < ns0:SHIPMODE > ShipMode_4.2 < / ns0:SHIPMODE >

    < / ns0:P_LEG_ITEM >

    < / ns0:P_LEG >

    < / ns0:InputParameters >

    You can use recursive expressions function XQuery to browse down the tree (even if it's more than a job for XSLT), but in this case, it is probably easier to use a descendant axis:

    declare namespace ns0 = "http://xmlns.oracle.com/pcbpel/adapter/db/sp/GOP_DB_FSL_Msg_Persist_SVC";

    declare namespace ns1 = "http://www.example.org/INPUT";

    {

    for $i in $request / ns1:GlobalRoutePlanServiceGOPResponse / GlobalRoutePlanServiceResponse/response/legs / / leg

    where exists($i/Level)

    return

    {$i} / level/text)

    {$i} / ShipMode/text)

    }

    Output:

    http://xmlns.Oracle.com/pcbpel/adapter/DB/SP/GOP_DB_FSL_Msg_Persist_SVC">

    1

    ShipMode_1

    2

    ShipMode_2

    3.1

    ShipMode_3.1 &

    4.1

    ShipMode_4.1

    3.2

    ShipMode_3.2

    4.2

    ShipMode_4.2

  • Script to parse the XML data in Oracle DB

    Thank you for your time.

    I'm trying to use method 1 mentioned in answer 1 https://community.oracle.com/thread/1115266?tstart=0

    Please suggest how to change the method 1 XML part to adapt my XML?

    I am also including the code mentioned in method 1 for convenience

    Create or replace procedure parse_xml is
      l_bfile   BFILE;
      l_clob    CLOB;
      l_parser  dbms_xmlparser.Parser;
      l_doc     dbms_xmldom.DOMDocument;
      l_nl      dbms_xmldom.DOMNodeList;
      l_n       dbms_xmldom.DOMNode;
      l_file      dbms_xmldom.DOMNodeList;
      l_filen       dbms_xmldom.DOMNode;
      lv_value VARCHAR2(1000);
       l_ch      dbms_xmldom.DOMNode;
    
    l_partname varchar2(100);
    l_filename varchar2(1000);
      l_temp    VARCHAR2(1000);
      TYPE tab_type IS TABLE OF tab_software_parts%ROWTYPE;
      t_tab  tab_type := tab_type();
    BEGIN
      l_bfile := BFileName('DIR1', 'SoftwareParts.xml');
      dbms_lob.createtemporary(l_clob, cache=>FALSE);
      dbms_lob.open(l_bfile, dbms_lob.lob_readonly);
      dbms_lob.loadFromFile(dest_lob => l_clob,    src_lob  => l_bfile,    amount   => dbms_lob.getLength(l_bfile));
      dbms_lob.close(l_bfile); 
      dbms_session.set_nls('NLS_DATE_FORMAT','''DD-MON-YYYY''');
      
      l_parser := dbms_xmlparser.newParser;
      
      dbms_xmlparser.parseClob(l_parser, l_clob);
      l_doc := dbms_xmlparser.getDocument(l_parser);
        dbms_lob.freetemporary(l_clob);
      dbms_xmlparser.freeParser(l_parser);
      
      l_nl := dbms_xslprocessor.selectNodes(dbms_xmldom.makeNode(l_doc),'/PartDetails/Part');
      
        FOR cur_emp IN 0 .. dbms_xmldom.getLength(l_nl) - 1 LOOP
        l_n := dbms_xmldom.item(l_nl, cur_emp);
        t_tab.extend;
      
        dbms_xslprocessor.valueOf(l_n,'Name/text()',l_partname);
        t_tab(t_tab.last).partname := l_partname;
        l_file := dbms_xslprocessor.selectNodes(l_n,'Files/FileName');
    
        FOR cur_ch IN 0 .. dbms_xmldom.getLength(l_file) - 1 LOOP
          l_ch := dbms_xmldom.item(l_file, cur_ch);
          lv_value := dbms_xmldom.getnodevalue(dbms_xmldom.getfirstchild(l_ch));
          
          if t_tab(t_tab.last).partname is null then t_tab(t_tab.last).partname := l_partname; end if;
          t_tab(t_tab.last).filename := lv_value;
        t_tab.extend;
        
       END LOOP;
    
       END LOOP;
        t_tab.delete(t_tab.last);
      
      FOR cur_emp IN t_tab.first .. t_tab.last LOOP
      
      if t_tab(cur_emp).partname is not null and  t_tab(cur_emp).filename is not null then
        INSERT INTO tab_software_parts
        VALUES
        (t_tab(cur_emp).partname, t_tab(cur_emp).filename);
        end if;
        
      END LOOP;
      COMMIT;
    
      dbms_xmldom.freeDocument(l_doc);
    EXCEPTION
      WHEN OTHERS THEN
        dbms_lob.freetemporary(l_clob);
        dbms_xmlparser.freeParser(l_parser);
        dbms_xmldom.freeDocument(l_doc);
    END;
    
    
    
    

    I have an XML file in the following format.

    < TWObject className = "TWObject" >

    < array size = "240" >

    < item >

    < type variable = "QuestionDetail" >

    < questionId type = "String" > <! [CDATA [30]] > < / questionId >

    < questionType type = "questionType" > <! [CDATA [COUNTRY]] > < / questionType >

    < type country = "String" > <! [CDATA [GB]] > < / country >

    < questionText type = "String" > <! [CDATA [Please indicate whether the following "market research Type" applies to your project: < br > < br > detail followed or Message reminds me of a study put in service in a list of call/target Lilly]] > < / questionText >

    < optionType type = "String" > <! [CDATA [RadioButton]] > < / optionType >

    < answerOptions type = 'String []' >

    < point > <! [CDATA [Yes]] > < / item >

    < point > <! [CDATA [n]] > < / item >

    < / answerOptions >

    < ruleId type = "String" > <! [CDATA [CRP_GB001]] > < / ruleId >

    < parentQuestionId type = "String" > < / parentQuestionId >

    < parentQuestionResp type = "String" > < / parentQuestionResp >

    < / variable >

    < / point >

    < / array >

    < / TWObject >

    If you get a chain of about 512K size then it must be be provided as a CLOB as a varchar2 cannot accept that 32767 bytes (1 byte out of 32K).

    So, you probably want something like this...

    Create procedure textxmlpro (str in clob) is

    Start

    insert into whatevertable

    Select x.rn

    x.item_type

    x.questionid

    x.questiontype

    x.country

    x.questiontext

    x.optiontype

    y.opt_rn

    y.item

    x.ruleId

    x.parentquestionid

    x.parentquestionresp

    from xmltable ('/ TWObject/table/point ')

    by the way of xmltype (str)

    columns for the ordinalite RN

    , path of varchar2 (15) of item_type '. / variable/@type'

    , path of varchar2 (5) questionid '. / variable/questionId '

    , path of varchar2 (10) of questiontype '. / variable/questionType '

    , path of countries varchar2 (5) '. / variable/country '

    , path of varchar2 (40) of questiontext '. / variable/questionText '

    , path of varchar2 (15) of optiontype '. / variable/optionType '

    , answerOptions xmltype path '. / variable/answerOptions '

    , path of varchar2 (10) RuleID '. / variable/rule ID '

    , path of varchar2 (5) of parentquestionid '. / variable/parentQuestionId '

    , path of varchar2 (5) of parentquestionresp '. / variable/parentQuestionResp '

    ) x

    , xmltable ('/ answerOptions/point ')

    in passing x.answerOptions

    columns for the ordinalite opt_rn

    , path of varchar2 (5) point '.'

    ) y ;

    end;

    Who is using XMLTYPE (.. clobvariable..) on the clause of "passage" to the XMLTABLE statement (no need for WITH t... in your case). He also does insert it into your table as with any normal insert into... select statement.

Maybe you are looking for