Parsing XML attributes

Hi.
I have the following example of XML structure :
create table xxx (xmlval xmltype);
insert into xxx values (xmltype('<?xml version="1.0" encoding="utf-8"?> <Records> <Card P1="10" P2="20" /> </Records>'));
I have written the following code :
declare
lx_xml_node xmltype;
l_str varchar2(100);
begin
select e.xmlval.extract('/Records/Card[1]') into lx_xml_node from xxx e;
select lx_xml_node.extract('/@Card/P1').getStringVal() into l_str from xxx e;
dbms_output.put_line(l_str);
end;
The problem is I cant get the value of P1 attibute (l_str IS NULL). Is there a way to extract P1 and P2 attribute from xml node? Any help or hint appreciated.
Thanks.

From your first post, I thought you were querying directly from the XMLType column.
If you're transferring the data to the PL/SQL engine then you immediately disable all possible optimizations, as Jason (A_Non) explained above.
Also note that in the query you gave, you're performing a cartesian join.
Since you're on 11.2, I think you should try out binary XML storage and measure the difference (it should be huge).
Here's a test case on a document containing 1000 Node3 :
SQL> drop table tmp_xml purge;
Table dropped.
SQL> create table tmp_xml of xmltype
  2  xmltype store as securefile binary xml;
Table created.
SQL> insert into tmp_xml values(xmltype(bfilename('XML_DIR','sample.xml'),nls_charset_id('AL32UTF8')));
1 row created.
SQL> commit;
Commit complete.
SQL> exec dbms_stats.gather_table_stats(user, 'TMP_XML');
PL/SQL procedure successfully completed.
SQL> select count(*)
  2  from tmp_xml t
  3     , xmltable('/Node1/Node2/Node3' passing t.object_value) x
  4  ;
  COUNT(*)
      1000
SQL> set timing on
SQL> set autotrace traceonly
SQL> SELECT t_hdr.h1,
  2         t_hdr.h2,
  3         t_hdr.h3,
  4         t_hdr.h4,
  5         t_hdr.h5,
  6         t_hdr.h6,
  7         t_hdr.h7,
  8         t_rec.*
  9  FROM tmp_xml t
10     , XMLTable('/Node1'
11        passing t.object_value
12        columns
13          h1    VARCHAR2(5)  path 'h1',
14          h2    VARCHAR2(14) path 'h2',
15          h3    VARCHAR2(14) path 'h3',
16          h4    VARCHAR2(14) path 'h4',
17          h5    VARCHAR2(14) path 'h5',
18          h6    VARCHAR2(50) path 'h6',
19          h7    VARCHAR2(14) path 'h7',
20          Node2 XMLType      path 'Node2'
21       ) t_hdr
22     , XMLTable('/Node2/Node3'
23        passing t_hdr.Node2
24        columns
25          rc1  VARCHAR2(21) path '@rc1',
26          rc2  VARCHAR2(5)  path '@rc2',
27          rc3  VARCHAR2(17) path '@rc3',
28          rc4  VARCHAR2(17) path '@rc4',
29          rc5  VARCHAR2(17) path '@rc5',
30          rc6  VARCHAR2(17) path '@rc6',
31          rc7  VARCHAR2(5)  path '@rc7',
32          rc8  VARCHAR2(12) path '@rc8',
33          rc9  VARCHAR2(12) path '@rc9',
34          rc10 VARCHAR2(32) path '@rc10',
35          rc11 VARCHAR2(32) path '@rc11',
36          rc12 VARCHAR2(32) path '@rc12',
37          rc13 VARCHAR2(5)  path '@rc13',
38          rc14 VARCHAR2(7)  path '@rc14',
39          rc15 VARCHAR2(32) path '@rc15',
40          rc16 VARCHAR2(29) path '@rc16',
41          rc17 VARCHAR2(4)  path '@rc17',
42          rc18 VARCHAR2(6)  path '@rc18',
43          rc19 VARCHAR2(11) path '@rc19',
44          rc20 VARCHAR2(11) path '@rc20',
45          rc21 VARCHAR2(13) path '@rc21',
46          rc22 VARCHAR2(12) path '@rc22',
47          rc23 VARCHAR2(5)  path '@rc23',
48          rc24 VARCHAR2(4)  path '@rc24',
49          rc25 VARCHAR2(17) path '@rc25',
50          rc26 VARCHAR2(14) path '@rc26',
51          rc27 VARCHAR2(3)  path '@rc27',
52          rc28 VARCHAR2(3)  path '@rc28',
53          rc29 VARCHAR2(17) path '@rc29',
54          rc30 VARCHAR2(5)  path '@rc30',
55          rc31 VARCHAR2(11) path '@rc31',
56          rc32 VARCHAR2(11) path '@rc32',
57          rc33 VARCHAR2(11) path '@rc33',
58          rc34 VARCHAR2(11) path '@rc34',
59          rc35 VARCHAR2(11) path '@rc35',
60          rc36 VARCHAR2(11) path '@rc36',
61          rc37 VARCHAR2(11) path '@rc37',
62          rc38 VARCHAR2(11) path '@rc38',
63          rc39 VARCHAR2(11) path '@rc39',
64          rc40 VARCHAR2(11) path '@rc40',
65          rc41 VARCHAR2(11) path '@rc41',
66          rc42 VARCHAR2(11) path '@rc42',
67          rc43 VARCHAR2(11) path '@rc43',
68          rc44 VARCHAR2(11) path '@rc44',
69          rc45 VARCHAR2(11) path '@rc45',
70          rc46 VARCHAR2(11) path '@rc46'
71       ) t_rec
72  ;
1000 rows selected.
Elapsed: 00:00:01.22
Execution Plan
Plan hash value: 2982218919
| Id  | Operation           | Name    | Rows  | Bytes | Cost (%CPU)| Time     |
|   0 | SELECT STATEMENT    |         |    66M|    11G|   222K  (1)| 00:44:29 |
|   1 |  NESTED LOOPS       |         |    66M|    11G|   222K  (1)| 00:44:29 |
|   2 |   NESTED LOOPS      |         |  8168 |  1427K|    32   (0)| 00:00:01 |
|   3 |    TABLE ACCESS FULL| TMP_XML |     1 |    87 |     3   (0)| 00:00:01 |
|   4 |    XPATH EVALUATION |         |       |       |            |          |
|   5 |   XPATH EVALUATION  |         |       |       |            |          |
Statistics
          8  recursive calls
          0  db block gets
       8791  consistent gets
          0  physical reads
          0  redo size
      23347  bytes sent via SQL*Net to client
       1145  bytes received via SQL*Net from client
         68  SQL*Net roundtrips to/from client
          0  sorts (memory)
          0  sorts (disk)
       1000  rows processed

Similar Messages

  • How to generate GUI code from parsed XML file?

    hai,
    I have to generate GUI code after parsing any configuration XML file as input.Now i have parsed my XML file and got its attributed and i want to get some idea of how to map the parsed XML attributes to the java code to build GUI code.

    Hello,
    1. I like to create data type from a XML file structure, which contains the data structure ?
    XML fields will need to be taken note of to see which is repeating or not. You can also load the XML into a third-party tool such as Altova XML Spy and then generate an XSD from there. You will need to import the XSDs into PI under external definitions. However, this does not guarantee business interoperability, as such, it is always best to ask the provider for the XSDs or WSDL. It will also save you a lot of time from guessing which fields are needed or not.
    2. How to create custom node function in graphical mapping editor ?
    In your graphical mapping editor, on the lowest left corner, there is an icon there that says Create New Function. You must take into account their return types:
    1. Single Values = String
    2. Queue/Context (no return type) thus resultList is used.
    Hope this helps,
    Mark

  • Safari XML parser converts attributes to lower case?

    I am trying to create and serialize XML documents using Safari 2.01. It appears that during this process, XML attributes are always converted to lower case. Since XML is case sensitive, this causes errors when mixed case is expected. My sample code (below) works properly (attributes not converted to lower case) in FireFox, Netscape, etc.
    Questions are:
    Is there a way to load/serizlize XML in Safari so that this does not happen?
    If not, is this behavior by design or is it a bug? Will this be changed in future versions?
    Thanks for any assistance!
    Sample code:
    // Create XML document
    var xmlString = '<Test MixedCase="test">SomeText</Test>'
    var parser = new DOMParser();
    xmlDoc = parser.parseFromString(xmlString, "text/xml");
    // Get XML text
    var serializer = new XMLSerializer();
    text = serializer.serializeToString(xmlDoc);
    IBM Thinkpad T40   Windows 2000  
    IBM Thinkpad T40   Windows 2000  
      Windows XP  
      Mac OS X (10.2.x)  
      Mac OS X (10.0.x)  

    Are you sure the parser is changing the element names?
    (You didn't really mean "attributes", did you?) If it
    is, then that's a bug in the parser. Element names in
    XML are case-sensitive, i.e. they can be upper or
    lower case or any mixture of cases. There aren't
    supposed to be any "features" that let you fiddle with
    the case of element names.
    If you told me that you were using a Transformer to
    produce HTML, and that it was outputting <TR>, I
    wouldn't be surprised. Especially since XALAN is a
    transformer and not a parser. I would just suggest in
    that case that you should change your output method
    from HTML to XML, and to output <tr>. A Transformer
    won't change the case of element names if the output
    method is XML, but it may if the output method is
    HTML.Thanks for the response. Sorry about the vernacular mixup there.
    Here is our situation:
    javax.xml.parsers.SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
    parser.parse(InputSource is, HandlerBase hb) <-- noted that this is a deprecated method
    This parse method here turns the html elements upper case.
    I have experimented with setting the XMLReader on the parser as a HTMLSerializer and XHTMLSerializer with no luck in changing the outcome.
    Hope this clears things up a bit more.

  • & and &amp; parser in XML attributes

    Let's say we have :
    cartoon="Tom & Jerry"
    has an attribute in our XML.
    Well Spry explodes and doesn't load the XML.
    The Spry parser doesn't seam to work. Any solution?

    & characters in XML attributes need to be entity encoded.
    Adding your attribute as is to an existing XML file and loading it
    in FireFox causes it to throw a "not well-formed" error. IE just
    silently fails.
    Try changing it to cartoon="Tom &amp; Jerry", that should
    work.
    On the Spry end of things, we could do a better Job about
    reporting XML format errors, but in IE it silently fails.
    --== Kin ==--

  • Urgent : Need help in parsing XML from Sharepoint and save it into DB

    Hi ,
    I am Sharepoint guy and a newbie in Oracle . PL/SQL
    I am using UTL_DBWS Package to call a Sharepoint WebService " and was sucessfull , Now the xml has to be parsed and stored into a Table. I am facing the issue as the XML has a different namesoace and normal XPATH query is not working
    Below is the XML and need help in parsing it
    declare
    responsexml sys.XMLTYPE;
    testparsexml sys.XMLTYPE;
    begin
    responsexml := sys.XMLTYPE('<GetListItemsResponse xmlns="http://schemas.microsoft.com/sharepoint/soap/">
    <GetListItemsResult>
    <listitems xmlns:s="uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882" xmlns:dt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882" xmlns:rs="urn:schemas-microsoft-com:rowset" xmlns:z="#RowsetSchema">
    <rs:data ItemCount="2">
    <z:row ows_MetaInfo="1;#" ows__ModerationStatus="0" ows__Level="1" ows_Title="Test Title 1" ows_ID="1" ows_owshiddenversion="1" ows_UniqueId="1;#{9C45D54E-150E-4509-B59A-DB5A1B97E034}" ows_FSObjType="1;#0" ows_Created="2009-09-12 17:13:16" ows_FileRef="1;#Lists/Tasks/1_.000"/>
    <z:row ows_MetaInfo="2;#" ows__ModerationStatus="0" ows__Level="1" ows_Title="Testing Tasks" ows_ID="2" ows_owshiddenversion="1" ows_UniqueId="2;#{8942E211-460B-422A-B1AD-1347F062114A}" ows_FSObjType="2;#0" ows_Created="2010-02-14 16:44:40" ows_FileRef="2;#Lists/Tasks/2_.000"/>
    </rs:data>
    </listitems>
    </GetListItemsResult>
    </GetListItemsResponse>');
    testparsexml := responsexml.extract('/GetListItemsResponse/GetListItemsResult/listitems/rs:data/z:row/@ows_Title');
    DBMS_OUTPUT.PUT_LINE(testparsexml.extract('/').getstringval());
    end;
    The issue is with rs:data , z:row nodes.... please suggest how to handle these kind of namespaces in Oracle
    I need the parse the attribute "ows_Title" and save it into a DB
    this script would generate "Error occured in XML Parsing"
    Help is appriciated, thanks for looking

    SQL> SELECT *
      FROM XMLTABLE (
              xmlnamespaces ('http://schemas.microsoft.com/sharepoint/soap/' as "soap",
                             '#RowsetSchema' AS "z"
              'for $i in //soap:*//z:row return $i'
              PASSING xmltype (
                         '<GetListItemsResponse xmlns="http://schemas.microsoft.com/sharepoint/soap/">
    <GetListItemsResult>
    <listitems xmlns:s="uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882" xmlns:dt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882" xmlns:rs="urn:schemas-microsoft-com:rowset" xmlns:z="#RowsetSchema">
    <rs:data ItemCount="2">
    <z:row ows_MetaInfo="1;#" ows__ModerationStatus="0" ows__Level="1" ows_Title="Test Title 1" ows_ID="1" ows_owshiddenversion="1" ows_UniqueId="1;#{9C45D54E-150E-4509-B59A-DB5A1B97E034}" ows_FSObjType="1;#0" ows_Created="2009-09-12 17:13:16" ows_FileRef="1;#Lists/Tasks/1_.000"/>
    <z:row ows_MetaInfo="2;#" ows__ModerationStatus="0" ows__Level="1" ows_Title="Testing Tasks" ows_ID="2" ows_owshiddenversion="1" ows_UniqueId="2;#{8942E211-460B-422A-B1AD-1347F062114A}" ows_FSObjType="2;#0" ows_Created="2010-02-14 16:44:40" ows_FileRef="2;#Lists/Tasks/2_.000"/>
    </rs:data>
    </listitems>
    </GetListItemsResult>
    </GetListItemsResponse>')
    columns ows_MetaInfo varchar2(20) path '@ows_MetaInfo',
             ows_Title varchar2(20) path '@ows_Title',
             ows__ModerationStatus varchar2(20) path '@ows__ModerationStatus'
    OWS_METAINFO         OWS_TITLE            OWS__MODERATIONSTATUS
    1;#                  Test Title 1         0                   
    2;#                  Testing Tasks        0                   
    2 rows selected.

  • File-Adapter: Variable substitution form payload XML-attribute

    Hi experts,
    is possible to use XML-attribute-content for variable substitution in file-Adapter?
    extract from XML:
    <?xml version="1.0" encoding="utf-8" ?>
    - <all>
    - <transaction <b>file="filename"</b>>
    - <table name="BPAADDRESS" options="insertIfUpdateFails">
    - <record id="1">
      <hkeycol name="BPAMAINHKEY">0010500345</hkeycol>
      <hkeycol name="USAGE">Invoice</hkeycol>
      </transaction>
    I want to get the value "filename" = attribute file of transaction.
    Is this possible?
    Thanks a lot,
    Florian

    I have done this taking a field from the XML.
    You have to map the location of the field within the XML...
    Taken from:
    http://help.sap.com/saphelp_nw04/helpdata/en/bc/bb79d6061007419a081e58cbeaaf28/frameset.htm
    Variable Substitution (Target Directory/File Name Scheme)
    If you set the Enable indicator, you can enter variables for the Target Directory and File Name Scheme. Enter the names of the variables and references in the table.
    &#9679;      Enter each variable that you reference in the Target Directory and File Name Scheme fields without the surrounding percentage sign under Name of Variables in the table.
    The variables can refer to attributes of the message header or elements of the message payload.
    &#9675;       If the variables are to refer to an attribute of the message header, add the prefix message: to the name of the variable under Reference. You can specify the following attributes of the message header:
    sender_party, sender_service, receiver_party, receiver_service, interface_name, interface_namespace,
    message_id (message ID with hyphens, for example 9fbe1ff1-9a0d-11d9-8665-cbf10a126331)
    message_id_hex (message ID in hexadecimal format, for example 9fbe1ff19a0d11d98665cbf10a126331)
    For example, if you want to specify the interface name from the message header in the target directory or in the file name scheme, enter message:interface_name as the reference.
    If one of the message attributes contains characters that are not permitted in a file name, for example \, /, :, *, ?, ", <, >, |, then these characters are replaced by an underscore ("_").
    &#9675;       If the variable refers to an element in XML schema, add the prefix payload: to the information under Reference. The reference then comprises a pseudo path description in the form of a comma-separated list with the schema namea,na,nameb,nb,....
    namea,nameb,... corresponds to the element name and na,nb,... corresponds to the occurrence of the element name at the respective level in the document.
    The description begins at the root of the document and ends at the respective element.
    To reference the element that is in bold in the example, the following expression is used: payload:root,1,e1,1,e2,2
    The parser searches for the first occurrence of the root element at the first level. It then searches for the first occurrence of e1 at the second level and for the second occurrence of e2 at the third level. The content of the last element (“Example Value”) is set as the value for a specified variable.
    <?xml version="1.0" encoding="UTF-8" ?>
    <root>
      <dummy>
         <e1>
            <e2>Data_1</e2>
            <f/>
            <g attr="abc">text</g>
            <e2>Data_2</e2>
         </e1>
      </dummy>
      <e1>
         <e2>illegal/value</e2>
         <f/>
         <g attr="abc">text</g>
         <e2 attr="fghij">Example Value</e2>
      </e1>
    </root>
    &#9679;      To disable the check the adapter performs for the element data, set the Disable Security Checks indicator.
    Otherwise, the adapter checks whether the element data contains characters that could lead to security risks in the file system environment. The check includes the characters “/“, “\“, and “..“.

  • How do you store parsed XML data in an array

    Hi, i am trying to complete a small program which implements the SAX parser to parse an XML file. My problem is that i am writing a custom class to store the parsed data into an array, and then make the array available to the main program via a simple method which returns the array. I know this must be very simple to do, but i seem to have developed a mental block with this part of the program. I can parse the data and print all the elements to the screen, but i just cant figure out how to store all the data elements into the array. I will post the class which is supposed to do this, and ask anyone out there if they know what i'm doing wrong, and also, if there is a more effeicient way of achieving this ( i expect there definitely is!! but i have never used the SAX parser before and am getting confused by the API docs on it!!) Any help very much appreciated.
    Here is my attempt at coding the class to handle the parsed XML data
    class Sink extends org.xml.sax.helpers.DefaultHandler
         implements org.xml.sax.ContentHandler{
    Customer[] customers = new Customer[20];
         int count = 1;
         int x = 0;
         int tagCount = 0;
         String name;
    String custID;
         String username;
         String address;
         String phoneNum;
    public void startElement(String uri, String localName, String rawName, final org.xml.sax.Attributes attributes)throws org.xml.sax.SAXException{
    //count the number of <name> tags in the XML file
         if(rawName.equals("name")){
              tagCount++;
    public void characters(char[] ch, int start, int len){
    //get the current string
         String text = new String(ch, start, len);
         String text1 = text.trim();
    //there are 5 elements for each customer found in the XML file so when the count reaches 6
    // i reset this to 1
         if(count == 6){
         count = count - 5;
         if(text1.length()>0 && count == 1){
              name = text1;
              System.out.println(name);
              }else{
         if(text1.length()>0 && count == 2){
              custID = text1;
              System.out.println(custID);
                   }else{
                   if(text1.length()>0 && count == 3){
                   username = text1;
                   System.out.println(username);
                   }else{
                        if(text1.length()>0 && count == 4){
                        address = text1;
                        System.out.println(address);
                        }else{
                        if(text1.length()>0 && count == 5){
                             phoneNum = text1;
                             System.out.println(phoneNum);
                             //add data to the customer array
                             customers[x] = new Customer(name, custID, username, address, phoneNum);
    // increment the array index counter
                        x = x+1;
                        }//end of if
                        }//end else
                        }//end else
                   }//end else
              }//end else
    }//end of characters method
    public void endDocument(){
         System.out.println("There are " + tagCount +
         " <name> elements.");
    }//end of class Sink
    Before the end of this class i also need to make the array available to the calling program!!
    Any help would be much appreciated
    Thanks
    Iain

    Ok, yer going about this all the wrong way. You shouldn't have to maintain a count of all the elements. Basically you are locking yourself into the XML tags not only all being there but are assuming they are all in the same order. What you should do is in your characters() method, put all of the characters into a string buffer. Then, in endElement() (which you dont use btw, you should) you grab the information that is in the string buffer and store it into your Customer object depending on what the tagName is.
    Also, you should probably use a List to store all the Customer objects and not an single array, it's more dynamic and you arent locked into a set number of Customers.
    I wont do it all for you, but I'll give you a good outline to use.
    public class CustomerHandler extends DefaultHandler {
        private java.util.List customerList;  // List of Customer objects
        private java.util.StringBuffer buf;   // StringBuffer to store the string of characters between the start and end tags
        private Customer customer;  // Customer object that is initialized with each entry.
        public CustomerHandler() {
            customerList = new java.util.ArrayList();   // Initialize the List
            buf = new java.util.StringBuffer();   // Initialize the string buffer
        //  Make your customer list available to other classes
        public java.util.List getCustomerList() {
            return customerList;
        public void startElement(String nsURI, String sName, String tagName, Attributes attributes) throws SAXException {
            // Clear the String Buffer
            //  If the tagName is "Customer" then create a new Customer object
        public void characters(char[] ch, int start, int length) {
            //  append the characters into the string buffer
        public void endElement(String nsURI, String sName, String tagName) throws SAXException {
            // If the tagName is "Customer" add your customer object to the List
            // Place the data from the String Buffer into a String
            //  Depending on the tagName, call the appropriate set method on your customer object
    }

  • How to parse XML to Java object... please help really stuck

    Thank you for reading this email...
    If I have a **DTD** like:
    <!ELEMENT person (name, age)>
    <!ATTLIST person
         id ID #REQUIRED
    >
    <!ELEMENT name ((family, given) | (given, family))>
    <!ELEMENT age (#PCDATA)>
    <!ELEMENT family (#PCDATA)>
    <!ELEMENT given (#PCDATA)>
    the **XML** like:
    <person id="a1">
    <name>
         <family> Yoshi </family>
         <given> Samurai </given>
    </name>
    <age> 21 </age>
    </person>
    **** Could you help me to write a simple parser to parse my DTD and XML to Java object, and how can I use those objects... sorry if the problem is too basic, I am a beginner and very stuck... I am very confuse with SAXParserFactory, SAXParser, ParserAdapter and DOM has its own Factory and Parser, so confuse...
    Thank you for your help, Yo

    Hi, Yo,
    Thank you very much for your help. And I Wish you are there...I'm. And I plan to stay - It's sunny and warm here in Honolulu and the waves are up :)
    A bit more question for dear people:
    In the notes, it's mainly focus on JAXB,
    1. Is that mean JAXB is most popular parser for
    parsing XML into Java object? With me, definitely. There are essentially 3 technologies that allow you to parse XML documents:
    1) "Callbacks" (e.g. SAX in JAXP): You write a class that overrides 3 methods that will be called i) whenever the parser encounters a start tag, ii) an end tag, or iii) PCDATA. Drawback: You have to figure out where the heck in the document hierarchy you are when such a callback happens, because the same method is called on EACH start tag and similarly for the end tag and the PCDATA. You have to create the objects and put them into your own data structure - it's very tedious, but you have complete control. (Well, more or less.)
    2) "Tree" (e.g. DOM in JAXP, or it's better cousin JDOM): You call a parser that in one swoop creates an entire hierarchy that corresponds to the XML document. You don't get called on each tag as with SAX, you just get the root of the resulting tree. Drawback: All the nodes in the tree have the same type! You probably want to know which tags are in the document, don't you? Well, you'll have to traverse the tree and ask each node: What tag do you represent? And what are your attributes? (You get only strings in response even though your attributes often represent numbers.) Unless you want to display the tree - that's a nice application, you can do it as a tree model for JTree -, or otherwise don't care about the individual tags, DOM is not of much help, because you have to keep track where in the tree you are while you traverse it.
    3) Enter JAXB (or Castor, or ...): You give it a grammar of the XML documents you want to parse, or "unmarshall" as the fashion dictates to call it. (Actually the name isn't that bad, because "parsing" focuses on the input text while "unmarshalling" focuses on the objects you get, even though I'd reason that it should be marshalling that converts into objects and unmarshalling that converts objects to something else, and not vice versa but that's just my opinion.) The JAXB compiler creates a bunch of source files each with one (or now more) class(es) (and now interfaces) that correspond to the elements/tags of your grammar. (Now "compiler" is a true jevel of a misnomer, try to explain to students that after they run the "compiler", they still need to compile the sources the "compiler" generated with the real Java compiler!). Ok, you've got these sources compiled. Now you call one single method, unmarshall() and as a result you get the root node of the hierarchy that corresponds to the XML document. Sounds like DOM, but it's much better - the objects in the resulting tree don't have all the same type, but their type depends on the tag they represent. E.g if there is the tag <ball-game> then there will be an object of type myPackage.BallGame in your data structure. It gets better, if there is <score> inside <ball-game> and you have an object ballGame (of type BallGame) that you can simply call ballGame.getScore() and you get an object of type myPackage.Score. In other words, the child tags become properties of the parent object. Even better, the attributes become properties, too, so as far as your program is concerned there is no difference whether the property value was originally a tag or an attribute. On top of that, you can tell in your schema that the property has an int value - or another primitive type (that's like that in 1.0, in the early release you'll have to do it in the additional xjs file). So this is a very natural way to explore the data structure of the XML document. Of course there are drawbacks, but they are minor: daunting complexity and, as a consequence, very steep learning curve, documentation that leaves much to reader's phantasy - read trial and error - (the user's guide is too simplicistic and the examples too primitive, e.g. they don't even tell you how to make a schema where a tag has only attributes) and reference manual that has ~200 pages full of technicalities and you have to look with magnifying glas for the really usefull stuff, huge number of generated classes, some of which you may not need at all (and in 1.0 the number has doubled because each class has an accompanying interface), etc., etc. But overall, all that pales compared to the drastically improved efficiency of the programmer's efforts, i.e. your time. The time you'll spend learning the intricacies is well spent, you'll learn it once and then it will shorten your programming time all the time you use it. It's like C and Java, Java is order of magnitude more complex, but you'd probably never be sorry you gave up C.
    Of course the above essay leaves out lots and lots of detail, but I think that it touches the most important points.
    A word about JAXB 1.0 vs. Early Release (EA) version. If you have time, definitively learn 1.0, they are quite different and the main advantage is that the schema combines all the info that you had to formulate in the DTD and in the xjs file when using the EA version. I suggested EA was because you had a DTD already, but in retrospect, you better start from scratch with 1.0. The concepts in 1.0 are here to stay and once your surmounted the learning curve, you'll be glad that you don't have to switch concepts.
    When parser job is done,
    what kind of Java Object we will get? (String,
    InputStream or ...)See above, typically it's an object whose type is defined as a class (and interface in 1.0) within the sources that JABX generates. Or it can be a String or one of the primitive types - you tell the "compiler" in the schema (xjs file in EA) what you want!
    2. If we want to use JAXB, we have to contain a
    XJS-file? Something like:In EA, yes. In 1.0 no - it's all in the schema.
    I am very new to XML, is there any simpler way to get
    around them? It has already take me 4 days to find a
    simple parser which give it XML and DTD, then return
    to me Java objects ... I mean if that kind of parser
    exists....It'll take you probably magnitude longer that that to get really familiar with JAXB, but believe me it's worth it. You'll save countless days if not weeks once you'll start developing serious software with it. How long did it take you to learn Java and it's main APIs? You'll either invest the time learning how to use the software others have written, or you invest it writing it yourself. I'll take the former any time. But it's only my opinion...
    Jan

  • How to parse xml in java

    i wrote java client to invoke webservice(TIBCO) as a result i am getting back xml. now i have to parse xml and use the information. can anyone pls advise on this.
    thanks

    There are two kinds of parser available. One converts the XML to a Document Object Model (DOM). This is a heirarchy of Node objects each of which represents an element of XML, a tag, an attribute a piece of text etc.. Then you walk the graph extracting what you want.
    The other kind is the SAX event parser. You give this a callback (extends DefaultHandler) and it calls appropriate methods for each element as it's encountered.
    The second method is probably slight more complex to use but will deal with files of unlimited size without huge memory usage.
    In both cases you get the parser using a Factory/Interface pattern. You'll find the factory classes in javax.xml.parsers. The rest of the DOM stuff is in org.w3c.dom and the SAX stuff in org.xml.sax.

  • How to parse xml

    Hi All
    I want to parse xml document which contains more then one occurrence of particular element.
    I want to get some sub elements of that element and want take action on the basis of param tag inside this sub element.
    for example :
    <appender name="first" class="tempclass...">
    <param name="File" value="d:/test.log" />
    <filter class="">
    <param name="LevelToMatch" value="sdsds" />
    <param name="OtherParam" value="bla bla" />
    </filter>
    </appender>
    <appender name="second" class="tempclass...">
    </appender>
    my problem is how do i differentiate all "<appender>".
    I want values of "File" and "LevelToMatch" for each declaired appender
    and depending upon the values i want to take some decision.
    I dont know XML much
    I am using DOM parser.
    Please help me ASAP.
    Thanks in advance,

    hi,
    i hope u need to get the attribute values, right...
    if yes..create the DocumentBuilderFactory for the xml the uisng buildFactory method u will get the parser...from parser u cann go for anything....
    if u r not clearly, reply where do u struck...
    bye,
    suryakant.

  • How to Parse XML with SAX and Retrieving the Information?

    Hiya!
    I have written this code in one of my classes:
    /**Parse XML File**/
              SAXParserFactory factory = SAXParserFactory.newInstance();
              GameContentHandler gameCH = new GameContentHandler();
              try
                   SAXParser saxParser = factory.newSAXParser();
                   saxParser.parse(recentFiles[0], gameCH);
              catch(javax.xml.parsers.ParserConfigurationException e)
                   e.printStackTrace();
              catch(java.io.IOException e)
                   e.printStackTrace();
              catch(org.xml.sax.SAXException e)
                   e.printStackTrace();
              /**Parse XML File**/
              games = gameCH.getGames();And here is the content handler:
    import java.util.ArrayList;
    import org.xml.sax.*;
    import org.xml.sax.helpers.DefaultHandler;
    class GameContentHandler extends DefaultHandler
         private ArrayList<Game> games = new ArrayList<Game>();
         public void startDocument()
              System.out.println("Start document.");
         public void endDocument()
              System.out.println("End document.");
         public void startElement(String namespaceURI, String localName, String qualifiedName, Attributes atts) throws SAXException
         public void endElement(String namespaceURI, String localName, String qualifiedName) throws SAXException
         public void characters(char[] ch, int start, int length) throws SAXException
              /**for (int i = start; i < start+length; i++)
                   System.out.print(ch);
         public ArrayList<Game> getGames()
              return games;
    }And here is the xml i am trying to parse:<?xml version="1.0" encoding="ISO-8859-1" standalone="yes"?>
    <Database>
         <Name></Name>
         <Description></Description>
         <CurrentGameID></CurrentGameID>
         <Game>
              <gameID></gameID>
              <name></name>
              <publisher></publisher>
              <platform></platform>
              <type></type>
              <subtype></subtype>
              <genre></genre>
              <serial></serial>
              <prodReg></prodReg>
              <expantionFor></expantionFor>
              <relYear></relYear>
              <expantion></expantion>
              <picPath></picPath>
              <notes></notes>
              <discType></discType>
              <owner></owner>
              <location></location>
              <borrower></borrower>
              <numDiscs></numDiscs>
              <discSize></discSize>
              <locFrom></locFrom>
              <locTo></locTo>
              <onLoan></onLoan>
              <borrowed></borrowed>
              <manual></manual>
              <update></update>
              <mods></mods>
              <guide></guide>
              <walkthrough></walkthrough>
              <cheats></cheats>
              <savegame></savegame>
              <completed></completed>
         </Game>
    </Database>I have been trying for ages and just can't get the content handler class to extract a gameID and instantiate a Game to add to my ArrayList! How do I extract the information from my file?
    I have tried so many things in the startElement() method that I can't actually remember what I've tried and what I haven't! If you need to know, the Game class instantiates with asnew Game(int gameID)and the rest of the variables are public.
    Please help someone...                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    OK, how's this?
    public void startElement(String namespaceURI, String localName, String qualifiedName, Attributes atts) throws SAXException
              current = "";
         public void endElement(String namespaceURI, String localName, String qualifiedName) throws SAXException
              try
                   if(qualifiedName.equals("Game") || qualifiedName.equals("Database"))
                        {return;}
                   else if(qualifiedName.equals("gameID"))
                        {games.add(new Game(Integer.parseInt(current)));}
                   else if(qualifiedName.equals("name"))
                        {games.get(games.size()-1).name = current;}
                   else if(qualifiedName.equals("publisher"))
                        {games.get(games.size()-1).publisher = current;}
                   etc...
                   else
                        {System.out.println("ERROR - Qualified Name found in xml that does not exist as databse field: " + qualifiedName);}
              catch (Exception e) {} //Ignore
         public void characters(char[] ch, int start, int length) throws SAXException
              current += new String(ch, start, length);
         }

  • Parsing XML files

    I'm trying to use XML Tools to parse and edit an XML file. I want to be able to parse attributes of various tags..for example..in the script below, how would I return the name of the content of 'image icon1.png' (which is 'One')?
    set theXML to parse XML "<?xml version=\"1.0\"?>
    <icons>
    <icon image='icon1.png' content='One'/>
    <icon image='icon2.png' content='Two'/>
    <icon image='icon3.png' content='Three'/>
    <icon image='icon4.png' content='Four'/>
    </icons>
    Thanks.
    Pedro

    Hello Pedro,
    In order to set certain element's attribute, try something like SCRIPT2 below.
    --SCRIPT2
    This will let /icons/icon\[@image = "icon3.png"]/@content := "some new number"
    Using XML Tools 2.8 (OS9) or 2.9 (OSX)
    http://www.latenightsw.com/freeware/XMLTools2/
    set doc to parse XML "<?xml version=\"1.0\"?>
    <icons>
    <icon image='icon1.png' content='One'/>
    <icon image='icon2.png' content='Two'/>
    <icon image='icon3.png' content='Three'/>
    <icon image='icon4.png' content='Four'/>
    </icons>
    set p to "icon3.png" as Unicode text -- # target value of /icons/icon/@image
    set q to "some new number" as Unicode text -- # replacement value of /icons/icon/@content
    tell doc
    if its class = XML document and XML tag = "icons" then -- /icons
    repeat with e in XML contents
    tell e's contents
    if its class = XML element and XML tag = "icon" then -- /icons/icon
    if XML attributes's image = p then -- /icons/icon/@image = p
    set XML attributes's content to q -- /icons/icon/@content := q
    end if
    end if
    end tell
    end repeat
    end if
    end tell
    return doc
    --END OF SCRIPT2
    And if I'm not mistaken about what you're trying to do, you may try something like SCRIPT2a below.
    --SCRIPT2a
    This will let /icons/icon\[@image = "icon1.png"]/@content := "any value",
    that is given as result of dialogue which will shown for each matching nodes.)
    Using XML Tools 2.8 (OS9) or 2.9 (OSX)
    http://www.latenightsw.com/freeware/XMLTools2/
    set doc to parse XML "<?xml version=\"1.0\"?>
    <icons>
    <icon image='icon1.png' content='One'/>
    <icon image='icon2.png' content='Two'/>
    <icon image='icon3.png' content='Three'/>
    <icon image='icon4.png' content='Four'/>
    </icons>
    set p to "icon1.png" -- # target value of /icons/icon/@image
    set q0 to "some new number" -- # default replacement value of /icons/icon/@content
    tell doc
    set i to 0 -- found node's seq number
    if its class = XML document and XML tag = "icons" then -- /icons
    repeat with e in XML contents
    tell e's contents
    if its class = XML element and XML tag = "icon" then -- /icons/icon
    set i to i + 1 -- increment node's seq number
    if XML attributes's image = p then -- /icons/icon/@image = p
    set q to XML attributes's content -- q := /icons/icon/@content
    set node to "/icons/icon\[" & i & "]"
    tell me
    display dialog ("Current node:" & return & ¬
    node & "/@image = " & p & return & ¬
    node & "/@content = " & q & return & return & ¬
    "Replacement @content value:") default answer q0
    set q to text returned of result
    end tell
    set XML attributes's content to q
    end if
    end if
    end tell
    end repeat
    end if
    end tell
    return doc
    --END OF SCRIPT2a
    Cheers,
    H
    PS. Copy code from this web page, not from subscribed email text, for I escaed some character, namely [, for posting.
    Message was edited by: Hiroto (fixed typo, etc)

  • Parsing xml using DOM parser in java

    hi there!!!
    i don have much idea about parsing xml.. i have an xml file which consists of details regarding indentation and spacing standards of C lang.. i need to read the file using DOM parser in java n store each of the attributes n elements in some data structure in java..
    need help as soon as possible!!!

    DOM is the easiest way to parse XML document, google for JDOM example it is very easy to implement.
    you need to know what is attribute, what is text content and what is Value in XML then easily you can parse your document with dom (watch for space[text#] in your XML document when you parse it).
    you get root node then nodelist of childs for root then go further inside, it is easy believe me.

  • How to compare after parsing xml file

    Hi,
    following code, parse the input.xml file, counts how many nodes are there and writes the node name and its value on screen.
    1) i am having trouble writing only node name into another file instead of writing to screen.
    2) after parsing, i like to compare each node name with another .xsd file for existence.
    Please keep in mind that, input.xml is based on some other .xsd and after parsing i have comparing its tag with another .xsd
    Need you help guys.
    thanks
    * CompareTags.java
    import java.io.*;
    import org.w3c.dom.*;
    import org.xml.sax.*;
    import javax.xml.parsers.*;
    import javax.xml.transform.*;
    import javax.xml.transform.dom.*;
    import javax.xml.transform.stream.*;
    /** This class represents short example how to parse XML file,
    * get XML nodes values and its values.<br><br>
    * It implements method to save XML document to XML file too
    public class CompareTags {
    private final static String xmlFileName = "C:/input.xml";
         int totalelements = 0;
    /** Creates a new instance of ParseXMLFile */
    public CompareTags() {
    // parse XML file -> XML document will be build
    Document doc = parseFile(xmlFileName);
    // get root node of xml tree structure
    Node root = doc.getDocumentElement();
    // write node and its child nodes into System.out
    System.out.println("Statemend of XML document...");
    writeDocumentToOutput(root,0);
                   System.out.println("totalelements in xyz tag " + totalelements);
              System.out.println("... end of statement");
    /** Returns element value
    * @param elem element (it is XML tag)
    * @return Element value otherwise empty String
    public final static String getElementValue( Node elem ) {
    Node kid;
    if( elem != null){
    if (elem.hasChildNodes()){
    for( kid = elem.getFirstChild(); kid != null; kid = kid.getNextSibling() ){
    if( kid.getNodeType() == Node.TEXT_NODE ){
    return kid.getNodeValue();
    return "";
    private String getIndentSpaces(int indent) {
    StringBuffer buffer = new StringBuffer();
    for (int i = 0; i < indent; i++) {
    buffer.append(" ");
    return buffer.toString();
    /** Writes node and all child nodes into System.out
    * @param node XML node from from XML tree wrom which will output statement start
    * @param indent number of spaces used to indent output
    public void writeDocumentToOutput(Node node,int indent) {
    // get element name
    String nodeName = node.getNodeName();
    // get element value
    String nodeValue = getElementValue(node);
    // get attributes of element
    NamedNodeMap attributes = node.getAttributes();
    System.out.println(getIndentSpaces(indent) + "NodeName: " + nodeName + ", NodeValue: " + nodeValue);
    for (int i = 0; i < attributes.getLength(); i++) {
    Node attribute = attributes.item(i);
    System.out.println(getIndentSpaces(indent + 2) + "AttributeName: " + attribute.getNodeName() + ", attributeValue: " + attribute.getNodeValue());
    // write all child nodes recursively
    NodeList children = node.getChildNodes();
              //int totalelements = 0;
    for (int i = 0; i < children.getLength(); i++) {
    Node child = children.item(i);
                   //     System.out.println("child value.."+child);
    if (child.getNodeType() == Node.ELEMENT_NODE) {
    writeDocumentToOutput(child,indent + 2);
                             if(node.getNodeName() == "DATA"){
                             totalelements = totalelements+1;}
                        //System.out.println("totalelements in DATA tag " + totalelements);
    /** Parses XML file and returns XML document.
    * @param fileName XML file to parse
    * @return XML document or <B>null</B> if error occured
    public Document parseFile(String fileName) {
    System.out.println("Parsing XML file... " + fileName);
    DocumentBuilder docBuilder;
    Document doc = null;
    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    docBuilderFactory.setIgnoringElementContentWhitespace(true);
    try {
    docBuilder = docBuilderFactory.newDocumentBuilder();
    catch (ParserConfigurationException e) {
    System.out.println("Wrong parser configuration: " + e.getMessage());
    return null;
    File sourceFile = new File(fileName);
    try {
    doc = docBuilder.parse(sourceFile);
    catch (SAXException e) {
    System.out.println("Wrong XML file structure: " + e.getMessage());
    return null;
    catch (IOException e) {
    System.out.println("Could not read source file: " + e.getMessage());
    System.out.println("XML file parsed");
    return doc;
    /** Starts XML parsing example
    * @param args the command line arguments
    public static void main(String[] args) {
    new CompareTags();
    }

    hi,
    check out the following links
    Check this blog to extract from XML:
    /people/kamaljeet.kharbanda/blog/2005/09/16/xi-bi-integration
    http://help.sap.com/saphelp_nw04/helpdata/en/fe/65d03b3f34d172e10000000a11402f/frameset.htm
    Check thi link for Extract from any DB:
    http://help.sap.com/saphelp_nw04s/helpdata/en/58/54f9c1562d104c9465dabd816f3f24/content.htm
    regards
    harikrishna N

  • XML attributes as a response

    My skills are rudimentary, I'm a new flex developer. I have
    done all of the tutorials and examples and I'm just struggling with
    using an XML attribute checking a response.
    I've written a simple flex 3 app to talk to Asterisk AJAM.
    I'm writing the login piece-- and i'm having trouble parsing this
    response from an http service (successful login) my problem comes
    in with the value not being as such
    <item>valuehere</item> it's part of the tag, an
    attribute i would suppose.:
    <ajax-response>
    <response type="object" id="unknown">
    <generic response="Success" message="Authentication
    accepted"/>
    </response>
    </ajax-response>
    What I have is a simple app with a http service and a login
    form. I have an event handler for the HTTP service, but I don't
    know how to parse for that generic response tag. Anyone know how to
    format an XML object for that type of response and throw a simple
    if statement looking for that attribute?
    Failure looks like this BTW:
    <ajax-response>

    <response type="object" id="unknown">
    <generic response="Error" message="Authentication
    failed"/>
    </response>
    </ajax-response>
    Thank you,
    Brian

    I've came up with the following code trying to use XML
    attributes from the response above--- it doesn't work but here is
    what I have (right now the if statement is commented out.... i'm
    trying to have it do an alert which doesn't work either):
    ---source---
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="
    http://www.adobe.com/2006/mxml"
    layout="absolute">
    <mx:states>
    <mx:State name="Logged In">
    <mx:SetProperty target="{panel1}" name="width"
    value="95%"/>
    <mx:SetProperty target="{panel1}" name="height"
    value="95%"/>
    <mx:RemoveChild target="{password}"/>
    <mx:RemoveChild target="{username}"/>
    <mx:RemoveChild target="{label1}"/>
    <mx:RemoveChild target="{Submit}"/>
    <mx:RemoveChild target="{label2}"/>
    <mx:SetProperty target="{panel1}" name="title"
    value="Once Logged In"/>
    <mx:AddChild relativeTo="{panel1}"
    position="lastChild">
    <mx:Label x="10" y="10" text="You properly
    authentictaed!"/>
    </mx:AddChild>
    <mx:AddChild relativeTo="{panel1}"
    position="lastChild">
    <mx:Label x="10" y="62" text="Label"/>
    </mx:AddChild>
    </mx:State>
    </mx:states>
    <mx:Script>
    <![CDATA[
    import mx.rpc.events.ResultEvent;
    var MyXML:XML;
    private function checkLogin(evt:ResultEvent):void
    MyXML = evt.result.channel.item;
    mx.controls.Alert.show(MyXML.@*);
    trace(MyXML.@*.toXMLString());
    /* if (MyXML.attribute(ajax-response.response.@generic) ==
    "Success") {
    if (MyXML.ajax-response.response.(@generic == "Success"))
    currentState = "Logged In";
    if (MyXML.ajax-response.response.(@generic == "Error"))
    mx.controls.Alert.show('Invalid username/password');
    ]]>
    </mx:Script>
    <mx:HTTPService id="login_user"
    result="checkLogin(event)" showBusyCursor="true" method="GET" url="
    http://72.22.224.90:8088/asterisk/mxml"
    useProxy="false">
    <mx:request xmlns="">
    <action>login</action>
    <username>
    {username.text}
    </username>
    <password>
    {password.text}
    </password>
    </mx:request>
    </mx:HTTPService>
    <mx:Panel resizeEffect="Resize" width="250" height="200"
    layout="absolute" title="Login System" horizontalCenter="0"
    verticalCenter="-2" id="panel1">
    <mx:Label x="10" y="10" text="Username:" id="label1"/>
    <mx:TextInput x="10" y="36" id="username"/>
    <mx:Label x="10" y="66" text="Password:" id="label2"/>
    <mx:TextInput x="10" y="92" id="password"
    displayAsPassword="true"/>
    <mx:Button x="10" y="122" label="Submit" id="Submit"
    click="login_user.send();"/>
    </mx:Panel>
    </mx:Application>

Maybe you are looking for

  • Error message: adobe mediacore CS6 has stopped working --????

    I am trying to run premiere elements 10 on a high=end pc with 8gb of memory, Win 7 Pro4-bit, massive hard drives and no conflicting software (that I can see....). Can open up the program and use the manage module. It shows me three files that I have

  • Streaming Album Cover Screen-Saver crash AND Fix

    I suffered from an ATV stutter/freeze and crash whenever I tried to stream music and use Album Cover Art as the screen-saver. I tried a small, no LARGE experiment (over 35,000 songs) in iTunes. I had *a lot* of Exotica and Space Age Pop from out of p

  • My macbook starting very slow i want to factory reset

    my macbook starting very slow i want to factory reset

  • Unable to increase table space

    Hi, i am getting this error on sap apoo 3.1 ides sytem ORA-001653 Unable to increase table space PSAPEL46DD # Can any one tell me who do i increase the tables space step by step Thanks Priya

  • My BT - "My Extras" will not load

    For some time now the My Extras section on My BT just refuses to load for me.  The spinning wheel goes on and on, and the content never loads.  I have tried this using both Safari and Firefox  with no luck.  My Extras does display normally on my iPad