Use of XML parser to read/parse xml stored in DB as CLOB

Hello,
I am new to XML technology. I have xml data stored in DB as
CLOB. I need to parse this data to retrieve VALUE fro certain
tags. I would greatly appreciate any help. Any examples that
manipulate xml data stored in DB can be of extreme help.
DesiDBA

As you use Oracle 9.0.1. We suggest you use XMLType instead of
CLOB to store your XML documents.
You can use xmlType.extract() to get the elements within the
XMLDocuments.
Please refer to our Oracle9i XML Demo for examples.
http://otn.oracle.com/tech/xml/xdk_sample/xdkdemo_faq.html
For Instructions:
http://ws5.olab.oracle.com/faqdemo/source/instruction.xsql?
pagename=ins_xmltype
Or you have to do the SQL query to get XML documents and parse
each document and extract the content yourself using XML Parser
for PL/SQL.
Thanks.

Similar Messages

  • XPATH not reading my xml properly.

    <?xml version="1.0"?>
    <xml class="1" index="0" xmlns="http://www.blablabla.com/lsr/blablalba"
         xmlns:testBase="http://www.blablabla.com/lsr/blablalba" service="localservicepreordering">
         <header>
              <testBase:interfaceid>testid</testBase:interfaceid>
              <testBase:actionrequired>No Validation</testBase:actionrequired>
              <testBase:applicationid>VFO</testBase:applicationid>
         </header>
         <lsng class="1" index="0">
              <pform>
                   <txnum class="0" index="0" fieldno="02">1187FRONTPO3A</txnum>
                   <dtsent class="0" index="0" fieldno="03">201001271341</dtsent>
                   <txtyp class="0" index="0" fieldno="04">B</txtyp>
                   <txact class="0" index="0" fieldno="05">U</txact>
                   <cc class="0" index="0" fieldno="07">ZBEL</cc>
                   <location>
                        <at class="0" index="0" fieldno="13">N</at>
                        <so class="0" index="0" fieldno="17">1600</so>
                        <sn class="0" index="0" fieldno="21">Market</sn>
                        <sh class="0" index="0" fieldno="22">St</sh>
                        <l1 class="0" index="0" fieldno="26">FL</l>
                        <l2 class="0" index="0" fieldno="27">17</l2>
                        <city class="0" index="0" fieldno="31">Philli</city>
                        <state class="0" index="0" fieldno="32">PA</state>
                        <zip class="0" index="0" fieldno="33">19103</zip>
                   </location>
                   <location>
                        <aft class="0" index="0" fieldno="13">N</aft>
                        <sano class="0" index="0" fieldno="17">1600</sano>
                        <sasn class="0" index="0" fieldno="21">Market</sasn>
                        <sath class="0" index="0" fieldno="22">St</sath>
                        <ld2 class="0" index="0" fieldno="26">FL</ld2>
                        <lv2 class="0" index="0" fieldno="27">17</lv2>
                        <city class="0" index="0" fieldno="31">Philli</city>
                        <state class="0" index="0" fieldno="32">PA</state>
                        <zip class="0" index="0" fieldno="33">19103</zip>
                   </location>
                   <rdata>
                        <reqnum class="0" index="0" fieldno="42">2159777290</reqnum>
                   </rdata>
              </pform>
         </lsing>
    </xml>
    I am trying to read this data using the xpath.. and its going crazy with out reading the xml.
    When I use the dom object to read this xml its failing to read the xml file.
    When i tried to remove the header part and read the xml file its working fine.
    I appreciate if some one can have the inputs in this.
    Thanks
    troubleshooter

    You aren't allowed to use element names which begin with "xml".

  • Read any XML File Elements using SAX Parser in J2se

    Hi All
    I can able to parsed one structured XML file using SAX
    Sample code :
    // ===========================================================
         // SAX DocumentHandler methods
         // ===========================================================
         public void startDocument() throws SAXException {
              logger.info("Start of document");
         public void endDocument() throws SAXException {
              logger.info("End of document");
         public void startElement(String namespaceURI, String localName, // local
                   // name
                   String qualName, // qualified name
                   Attributes attrs) throws SAXException {
              elemName = new String(localName); // element name
              if (elemName.equals(""))
                   elemName = new String(qualName); // namespaceAware = false
              tagPosition = TAG_START;
              // Set the string for accumulating the text in a tag to empty
              elemChars = "";
              // If the element name is "row", create a new row instance
              // If the element is "indexxid", "ModelPrice", or "ModelSpread",
              // the value will be read in the method "characters" and stored.
              if (elemName.equals("row")) {
                   row = new IndexRow();
                   numRows++;
              // logger.info("Number of numRow:"+numRows);
         } // end method startElement
         public void endElement(String namespaceURI, String simpleName, // simple
                   // name
                   String qualName // qualified name
         ) throws SAXException {
              elemName = new String(simpleName);
              if (elemName.equals(""))
                   elemName = new String(qualName); // namespaceAware = false
              tagPosition = TAG_END;
              String indexId = new String();
              Double dblVal = new Double(0);
              // If element name is "row", put the current row in the map for row
              // instances
              if (elemName.equals("row")) {
                   if (numRows <= 5) { logger.info("Row is: " + row.toString()); }
                   //ABX
                   //indexRows.put(row.getIndexxId(), row);
                   if (family.equals("ABX.HE")){
                   indexRows.put(row.getIndexREDId(), row);
                   else {
                        //CDX ITRXX
                             indexRows.put(row.getIndexxId(), row);
              } else if (elemName.equals("IndexID")) {
                   row.setIndexxId(elemChars);
                   // Leave double value at default of zero if there are no chars
                   if (elemChars.trim().length() != 0) {
                        dblVal = new Double(elemChars);
                        row.setCompositeSpread(dblVal);
                        indexId = row.getIndexxId();
              } else if (elemName.equals("REDCode")) {
                   row.setRedCode(elemChars);
              else if (elemName.equals("Name")) {
                   row.setRowName(elemChars);
              } else if (elemName.equals("Series")) {
                   row.setSeries(elemChars);
              } else if (elemName.equals("Version")) {
                   row.setVersion(elemChars);
              } else if (elemName.equals("Term")) {
                   row.setTerm(elemChars);
              } else if (elemName.equals("Maturity")) {
                   row.setMaturity(elemChars);
              } else if (elemName.equals("OnTheRun")) {
                   row.setOnTheRun(elemChars);
              } else if (elemName.equals("Date")) {
                   row.setRowDate(elemChars);
              } else if (elemName.equals("Depth")) {
                   row.setDepth(elemChars);
              else if (elemName.equals("Heat")) {
                   // logger.info("Chars for element " + elemName + " are '" +
                   // elemChars + "'");
                   // Leave double value at default of zero if there are no chars
                   if (elemChars.trim().length() != 0) {
                        dblVal = new Double(elemChars);
                        row.setHeat(dblVal);
                        indexId = row.getIndexxId();
    //          ABX.HE
              else if (elemName.equals("IndexREDId")){
                   row.setIndexREDId(elemChars);
              else if (elemName.equals("Coupon")){
                   row.setCoupon(elemChars);
              if (elemName.equals("Ontherun")) {
                   row.setOnTheRun(elemChars);
         } // end method endElement
         public void characters(char buf[], int offset, int len) throws SAXException {
              // If at end of element, there will be no characters
              if (tagPosition == TAG_END) {
                   return;
              // The characteres method may be called more than once
              // for an element if the internal buffer fills up.
              // Append the characters until the end of the element.
              String strVal = new String(buf, offset, len);
              elemChars = elemChars + strVal;
         } // end method characters
    } // end class MarkItIndexLoader
    but the problem is i want to read (parse) any XML file means any Elemets would be change any time using SAX .In the above example
    else if (elemName.equals("Heat")) {
    else if (elemName.equals("IndexREDId")){
    } else if (elemName.equals("Maturity")) {
    like above I am doing hard code Elements names and reading the values so i don't want hard coding the elements names I want to read any element name and value dynamically.
    If i give any one below XML file i want to read the Elements and displaying to console without changing any code i want to read the XML document.
    EX:
    Student.XML: <root>..</StName>..</StAge>...</root>
    Employee.XML: <root>..</EmpName>..</EmpAge>...</root>
    CdCatalog.XML: <root>..</Cdtitle>...</CdNumber>...</root>
    I need one java program can ready any type of XML file elements and send to the Database table.
    Please any one done like this task please suggest some reference links or books or sample snippet which can help me to develop program in my requirement.
    Thanks in advance
    Regards
    satish

    You should ask in the Java forum.
    Regards
    Stefan

  • Reading from XML file using DOM parser.

    Hi,
    I have written the following java code to read the XML file and print the values. It reads the XML file. It gets the node NAME and prints it. But it returns null when trying to get the node VALUE. I am unable to figure out why.
    Can anyone please help me with this.
    Thanks and Regards,
    Shweta
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import oracle.xml.parser.v2.*;
    import org.w3c.dom.*;
    import org.xml.sax.SAXException;
    public class ReadNodes
    private static XMLDocument mDoc;
    public ReadNodes () {
         try {
    DOMParser lParser = new DOMParser();
    URL lUrl = createURL("mot.xml");
    System.out.println("after creating the URL object ");
    lParser.setErrorStream(System.out);
    lParser.showWarnings(true);
    lParser.parse(lUrl);
    mDoc = lParser.getDocument();
         System.out.println("after creating the URL object "+mDoc);
    lParser.reset();
    } catch (Exception e) {
    e.printStackTrace();
    } // end catch block
    } // End of constructor
    public void read() throws DOMException {
    try {
         NodeList lTrans = this.mDoc.getElementsByTagName("TRANSLATION");
         for(int i=0;i<lTrans.getLength();i++) {
              NodeList lTrans1 = lTrans.item(i).getChildNodes();
              System.out.println("lTrans1.item(0).getNodeName : " + lTrans1.item(0).getNodeName());
              System.out.println("lTrans1.item(0).getNodeValue : " + lTrans1.item(0).getNodeValue());
              System.out.println("lTrans1.item(1).getNodeName : " + lTrans1.item(1).getNodeName());
              System.out.println("lTrans1.item(1).getNodeValue : " + lTrans1.item(1).getNodeValue());
         } catch (Exception e) {
         System.out.println("Exception "+e);
         e.printStackTrace();
         } catch (Throwable t) {
              System.out.println("Exception "+t);
    public static URL createURL(String pFileName) throws MalformedURLException {
    URL url = null;
    try {
    url = new URL(pFileName);
    } catch (MalformedURLException ex) {
    File f = new File(pFileName);
    String path = f.getAbsolutePath();
    String fs = System.getProperty("file.separator");
    System.out.println(" path of file : "+path +"separator " +fs);
    if (fs.length() == 1) {
    char sep = fs.charAt(0);
    if (sep != '/')
    path = path.replace(sep, '/');
    if (path.charAt(0) != '/')
    path = '/' + path;
    path = "file://" + path;
    System.out.println("path is : "+path);
    // Try again, if this throws an exception we just raise it up
    url = new URL(path);
    } // End catch block
    return url;
    } // end method create URL
    public static void main (String args[]) {
         ReadNodes mXML = new ReadNodes();
         mXML.read();
    The XML file that I am using is
    <?xml version = "1.0"?>
    <DOCUMENT>
    <LANGUAGE_TRANS>
    <TRANSLATION>
    <CODE>3</CODE>
    <VALUE>Please select a number</VALUE>
    </TRANSLATION>
    <TRANSLATION>
    <CODE>5</CODE>
    <VALUE>Patni</VALUE>
    </TRANSLATION>
    <TRANSLATION>
    <CODE>6</CODE>
    <VALUE>Status Messages</VALUE>
    </TRANSLATION>
    <TRANSLATION>
    <CODE>7</CODE>
    <VALUE>Progress</VALUE>
    </TRANSLATION>
    <TRANSLATION>
    <CODE>8</CODE>
    <VALUE>Create Data Files...</VALUE>
    </TRANSLATION>
    <TRANSLATION>
    <CODE>9</CODE>
    <VALUE>OK</VALUE>
    </TRANSLATION>
    </LANGUAGE_TRANS>
    </DOCUMENT>

    because what you want is not the node value of CODE but the node value of the text nodes into it!
    assuming only one text node into it, try this:
    System.out.println("lTrans1.item(0).getNodeName : " + lTrans1.item(0).getFirstChild().getNodeValue());

  • How to read xml-stylesheet Processing Instruction from XML using DOM Parser

    Hi,
    I am trying to read an xml that contains xsl stylesheet PI using DOMParser. The parse() method reads the entire contents of the XML except the PI instruction. Below is the XML I am using to read
    <?xml version="1.0" encoding="ISO-8859-1"?>
    <?xml-stylesheet href="../../../lang/en-us/style0/usc_profile.xsl" type="text/xsl"?>
    <Oblix oblang="en-us" xmlns="http://www.oblix.com/" xmlns:oblix="http://www.oblix.com/">
    <ObProfile>
    </ObProfile>
    </Oblix>
    Can anyone let me know if there are any propery settings to be done for the DOM parser before parsing?. If so, what is the property to be set?.
    Thanks in Advance
    Muthu

    A COTS product builds the XML and inserts the respective xsl (xml:stylesheet) file name to be used for transforming the xml. I am trying to interrupt this xml and make some updations on an element and finally send the updated xml to the stream.
    For the above process, I parse the input XML using DOMParser and update the elements (some internal elements). While I view the final XML that would be passed to the stream, I found the <?xml-stylesheet... PI is missing.
    I somehow managed using a temp fix by doing the below. I manually pulled the PI using document.getFirstChild().getNodeValue() and reconstructed the PI and inserted it to the outgoing XML. This needs to be done every time. This might run into problems when more than one PI is used in the XML.
    If the parsed XML could get the PI along with it the above problem could be resolved.
    Is there any property that could be set on the parser (prior to parsing) to resolve the issue?.

  • How to parse xml file to read the tags

    Hi All,
    I am having a requirement to read the tags from the xml file(xml parsing).
    The main issue is *xml file is stored in the table with xml type column* (not placed directly in the server) and we have to read the tags from that xml file.
    Please help me to achieve it.
    Regards,
    Akshata
    Edited by: Akshata on Mar 21, 2013 3:44 AM

    Hi,
    Akshata wrote:
    The main issue is xml file is stored in the table clob/blob type column (not placed directly in the server) and we have to read the tags from that xml file.How is that an issue? On the contrary, it's better when the data already resides in the database, though it should be in an XMLType column to leverage the full capacity of the Oracle parser.
    What's the datatype of the column exactly? CLOB or BLOB?
    Either way you'll have to convert in to XMLType datatype using the XMLType constructor.
    Did you go through the countless examples on this forum? Examples with XMLTable should be helpful.
    Post some sample data and database version if you need additional guidance.
    Thanks.

  • RE: (forte-users) XML Parser - Reading an XML document intothe Document

    Hi Laks
    Here is an example of converting a XML doc to a DOM object.
    The method is ParseXML(pXMLString:TextData, pListType:CSAListInterface).
    Hope this helps.
    Argyris Simakis
    Corporate Services Applications ITB
    Sydney AUSTRALIA
    -----Original Message-----
    From: Narayanan, Lakshmi [mailto:lnarayanoxhp.com]
    Sent: Thursday, April 06, 2000 8:31 AM
    To: 'kamranaminyahoo.com'
    Subject: (forte-users) XML Parser - Reading an XML document into the
    Document Object
    Importance: High
    Hi guys,
    I have been trying to read an XML file and feed it into the XMLParser.
    I have read about the DOM API, and i can work with the DOM API in java
    scripts. How
    will i play with it in TOOL implementation of DOM API. Can anyone guide me
    in this
    process.
    Thanks for your help.
    Laks
    For the archives, go to: http://lists.xpedior.com/forte-users and use
    the login: forte and the password: archive. To unsubscribe, send in a new
    email the word: 'Unsubscribe' to: forte-users-requestlists.xpedior.com

    Hi Laks
    Here is an example of converting a XML doc to a DOM object.
    The method is ParseXML(pXMLString:TextData, pListType:CSAListInterface).
    Hope this helps.
    Argyris Simakis
    Corporate Services Applications ITB
    Sydney AUSTRALIA
    -----Original Message-----
    From: Narayanan, Lakshmi [mailto:lnarayanoxhp.com]
    Sent: Thursday, April 06, 2000 8:31 AM
    To: 'kamranaminyahoo.com'
    Subject: (forte-users) XML Parser - Reading an XML document into the
    Document Object
    Importance: High
    Hi guys,
    I have been trying to read an XML file and feed it into the XMLParser.
    I have read about the DOM API, and i can work with the DOM API in java
    scripts. How
    will i play with it in TOOL implementation of DOM API. Can anyone guide me
    in this
    process.
    Thanks for your help.
    Laks
    For the archives, go to: http://lists.xpedior.com/forte-users and use
    the login: forte and the password: archive. To unsubscribe, send in a new
    email the word: 'Unsubscribe' to: forte-users-requestlists.xpedior.com

  • RE: (forte-users) XML Parser - Reading an XML document intothe D ocumen

    Hi Simakis,
    Your attachments explained the exact start i was looking for.
    Thanks a lot for sharing.
    Thanks
    Laks
    -----Original Message-----
    From: Simakis, Argyris [mailto:Argyris.Simakisdet.nsw.edu.au]
    Sent: Thursday, April 06, 2000 12:35 AM
    To: 'Narayanan, Lakshmi'
    Cc: 'kamranaminyahoo.com'
    Subject: RE: (forte-users) XML Parser - Reading an XML document into the
    D ocument Object
    Hi Laks
    Here is an example of converting a XML doc to a DOM object.
    The method is ParseXML(pXMLString:TextData, pListType:CSAListInterface).
    Hope this helps.
    Argyris Simakis
    Corporate Services Applications ITB
    Sydney AUSTRALIA
    -----Original Message-----
    From: Narayanan, Lakshmi [mailto:lnarayanoxhp.com]
    Sent: Thursday, April 06, 2000 8:31 AM
    To: 'kamranaminyahoo.com'
    Subject: (forte-users) XML Parser - Reading an XML document into the
    Document Object
    Importance: High
    Hi guys,
    I have been trying to read an XML file and feed it into the XMLParser.
    I have read about the DOM API, and i can work with the DOM API in java
    scripts. How
    will i play with it in TOOL implementation of DOM API. Can anyone guide me
    in this
    process.
    Thanks for your help.
    Laks
    For the archives, go to: http://lists.xpedior.com/forte-users and use
    the login: forte and the password: archive. To unsubscribe, send in a new
    email the word: 'Unsubscribe' to: forte-users-requestlists.xpedior.com

    Hi Simakis,
    Your attachments explained the exact start i was looking for.
    Thanks a lot for sharing.
    Thanks
    Laks
    -----Original Message-----
    From: Simakis, Argyris [mailto:Argyris.Simakisdet.nsw.edu.au]
    Sent: Thursday, April 06, 2000 12:35 AM
    To: 'Narayanan, Lakshmi'
    Cc: 'kamranaminyahoo.com'
    Subject: RE: (forte-users) XML Parser - Reading an XML document into the
    D ocument Object
    Hi Laks
    Here is an example of converting a XML doc to a DOM object.
    The method is ParseXML(pXMLString:TextData, pListType:CSAListInterface).
    Hope this helps.
    Argyris Simakis
    Corporate Services Applications ITB
    Sydney AUSTRALIA
    -----Original Message-----
    From: Narayanan, Lakshmi [mailto:lnarayanoxhp.com]
    Sent: Thursday, April 06, 2000 8:31 AM
    To: 'kamranaminyahoo.com'
    Subject: (forte-users) XML Parser - Reading an XML document into the
    Document Object
    Importance: High
    Hi guys,
    I have been trying to read an XML file and feed it into the XMLParser.
    I have read about the DOM API, and i can work with the DOM API in java
    scripts. How
    will i play with it in TOOL implementation of DOM API. Can anyone guide me
    in this
    process.
    Thanks for your help.
    Laks
    For the archives, go to: http://lists.xpedior.com/forte-users and use
    the login: forte and the password: archive. To unsubscribe, send in a new
    email the word: 'Unsubscribe' to: forte-users-requestlists.xpedior.com

  • Need to Parse or Read XML into a ResultSet

    Hi, I see lots of examples of folks reading from a database, populating a ResultSet, and then putting that data into an XML document. I don't see any reference to going the other way, and was hoping some of you might have an insight on how to do this.
    We have a huge historical database and want to take the older info, put it into xml format, zip it, and store the zip'd result as a blob. That's the easy part.
    We want to be able to go back, to read the blob, unzip it, and then populate a ResultSet and return that to the caller. I don't see any slick methodology to either 1.) instantiate an empty ResultSet or 2.) parse/read an XML structure into a ResultSet.
    Any bright ideas?
    Thanks, John

    @maggie: That is easily done with XPath expressions, for example:
    xmlstarlet sel -t -m '//servers[@country_code="us"]' -c '.' -n vpn.xml
    xmlstarlet sel -T -t -m '//servers[@country_code="us"]' -v @public_name -o " " -v @bw -n vpn.xml
    xmlstarlet sel -t -m '//servers[@country_code="us"]' -v '@public_name' -o ": " -v '@currentload' -n vpn.xml
    xmlstarlet sel -t -m '//servers[@country_code="us" and @currentload<15]' -v '@public_name' -o ": " -v '@currentload' -n vpn.xml
    xmlstarlet sel -t -m '//servers[@currentload<15]' -v '@public_name' -o ": " -v '@currentload' -n vpn.xml
    http://www.w3schools.com/xpath/default.asp
    Edit: If you use json and jshon, then you'll have to do the sorting and filtering in the shell
    jshon -e servers -a -e country_code -u -p -e public_name -u -p -e bw -u <vpn.json | {
    # filter country_code
    while read -r country_code && read -r public_name && read -r bw; do
    [ x"$country_code" = x"ca" ] && echo "$public_name $bw";
    done
    } | sort -k2,2nr -k1,1d # sort second field (bw) numeric reverse, if equal use dictionary sort on first (name)
    Last edited by progandy (2015-05-31 05:47:50)

  • HO w to use SAX parser to create an XML file on the fly

    Hi All,
    Currently I am using the DOM parser to create an XML file from a text file. But as the DOM takes much memory and inefficient, I need to convert the DOM translator to SAX translator. Can I do that ?? If YES then how to go about that and if NO then what may be the workaround for that.
    Please help me out
    Thanx in advance
    kaushik

    Incidentally, look at this thread:
    http://forum.java.sun.com/thread.jsp?forum=34&thread=252415
    It has an example of how to transform an XML file via XSLT. If you change this to use the zero-argument form of newTransformer, it will apply the "identity transformation" to your input, thus outputting your XML in valid form. Now you just need to figure out how to provide SAX input to this, and the JAXP download includes an example of that.

  • How to validate XML against XSD and parse/save in one step using SAXParser?

    How to validate XML against XSD and parse/save in one step using SAXParser?
    I currently have an XML file and XSD. The XML file specifies the location of the XSD. In Java code I create a SAXParser with parameters indicating that it needs to validate the XML. However, SAXParser.parse does not validate the XML, but it does call my handler functions which save the elements/attributes in memory as it is read. On the other hand, XMLReader.parse does validate the XML against the XSD, but does not save the document in memory.
    My code can call XMLReader.parse to validate the XML followed by SAXParser.parse to save the XML document in memory. But this sound inefficient. Besides, while a valid document is being parsed by XMLReader, it can be changed to be invalid and saved, and XMLReader.parse would be looking at the original file and would think that the file is OK, and then SAXParser.parse would parse the document without errors.
    <Book xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="book.xsd" name="MyBook">
      <Chapter name="First Chapter"/>
      <Chapter name="Second Chapter">
        <Section number="1"/>
        <Section number="2"/>
      </Chapter>
    </Book>
    <?xml version="1.0" encoding="ISO-8859-1" ?>
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="Book">
    <xs:complexType>
      <xs:sequence>
       <xs:element name="Chapter" minOccurs="0" maxOccurs="unbounded">
        <xs:complexType>
         <xs:sequence>
          <xs:element name="Section" minOccurs="0" maxOccurs="unbounded">
           <xs:complexType>
            <xs:attribute name="xnumber"/>
          </xs:complexType>
          </xs:element>
         </xs:sequence>
         <xs:attribute name="name"/>
        </xs:complexType>
       </xs:element>
      </xs:sequence>
      <xs:attribute name="name"/>
    </xs:complexType>
    </xs:element>
    </xs:schema>
    public class SAXXMLParserTest
       public static void main(String[] args)
          try
             SAXParserFactory factory = SAXParserFactory.newInstance();
             factory.setNamespaceAware(true);
             factory.setValidating(true);
             SAXParser parser = factory.newSAXParser();
             parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
                                "http://www.w3.org/2001/XMLSchema");
             BookHandler handler = new BookHandler();
             XMLReader reader = parser.getXMLReader();
             reader.setErrorHandler(handler);
             parser.parse("xmltest.dat", handler); // does not throw validation error
             Book book = handler.getBook();
             System.out.println(book);
             reader.parse("xmltest.dat"); // throws validation error because of 'xnumber' in the XSD
    public class Book extends Element
       private String name;
       private List<Chapter> chapters = new ArrayList<Chapter>();
       public Book(String name)
          this.name = name;
       public void addChapter(Chapter chapter)
          chapters.add(chapter);
       public String toString()
          StringBuilder builder = new StringBuilder();
          builder.append("<Book name=\"").append(name).append("\">\n");
          for (Chapter chapter: chapters)
             builder.append(chapter.toString());
          builder.append("</Book>\n");
          return builder.toString();
       public static class BookHandler extends DefaultHandler
          private Stack<Element> root = null;
          private Book book = null;
          public void startDocument()
             root = new Stack<Element>();
          public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException
             if (qName.equals("Book"))
                String name = attributes.getValue("name");
                root.push(new Book(name));
             else if (qName.equals("Chapter"))
                String name = attributes.getValue("name");
                Chapter child = new Chapter(name);
                ((Book)root.peek()).addChapter(child);
                root.push(child);
             else if (qName.equals("Section"))
                Integer number = Integer.parseInt(attributes.getValue("number"));
                Section child = new Section(number);
                ((Chapter)root.peek()).addSection(child);
                root.push(child);
          public void endElement(String uri, String localName, String qName) throws SAXException
             Element finished = root.pop();
             if (root.size() == 0)
                book = (Book) finished;
          public Book getBook()
             return book;
          public void error(SAXParseException e)
             System.out.println(e.getMessage());
          public void fatalError(SAXParseException e)
             error(e);
          public void warning(SAXParseException e)
             error(e);
    public class Chapter extends Element
       public static class Section extends Element
          private Integer number;
          public Section(Integer number)
             this.number = number;
          public String toString()
             StringBuilder builder = new StringBuilder();
             builder.append("<Section number=\"").append(number).append("\"/>\n");
             return builder.toString();
       private String name;
       private List<Section> sections = null;
       public Chapter(String name)
          this.name = name;
       public void addSection(Section section)
          if (sections == null)
             sections = new ArrayList<Section>();
          sections.add(section);
       public String toString()
          StringBuilder builder = new StringBuilder();
          builder.append("<Chapter name=\"").append(name).append("\">\n");
          if (sections != null)
             for (Section section: sections)
                builder.append(section.toString());
          builder.append("</Chapter>\n");
          return builder.toString();
    }Edited by: sn72 on Oct 28, 2008 1:16 PM

    Have you looked at the XML DB FAQ thread (second post) in this forum? It has some examples for validating XML against schemas.

  • Parse an Aggregate in XML Document using PL/SQL

    Hi. I've been successful with parsing a TAG in XML Document stored in CLOB using PL/SQL XML Parser.
    However, I need help on how to get the whole aggregate in XML Document stored in CLOB.
    sample XML Doc :
    <library>
    <book>
    <title>Oracle Complete Reference</title>
    <author>Kevin</Author>
    <year>2000</year>
    </book>
    <video>
    <title>Learning C++</title>
    <length>2 hours</length>
    <video>
    </library>
    I need a function that will accept an Input which is the aggregate name and will return the aggregate value.
    With the sample XML above, say the input is 'VIDEO', the function will return :
    <video>
    <title>Learning C++</title>
    <length>2 hours</length>
    <video>
    I'll really appreciate any help.
    null

    I used such an example to parse several Varchar2 strings in a given DB session:
    BEGIN
    parser := xmlparser.newparser ;
    xmlparser.parsebuffer(parser,xmlout) ;
    domdoc := xmlparser.getDocument(parser) ;
    xmlparser.FREEPARSER(parser) ;
    parser.id := -1 ;
    nodes := xslprocessor.selectNodes(
    xmldom.makenode(domdoc),
    'Positionen/Position') ;
    for i in 1 .. xmldom.getLength(nodes) loop
    node := xmldom.item(nodes,i-1) ;
    -- do s/thing with the node
    end loop ;
    xmldom.freedocument(domdoc) ;
    RETURN(komponenten) ;
    EXCEPTION
    WHEN OTHERS THEN
    if parser.id <> -1 then xmlparser.freeparser(parser) ;
    end if ;
    if domdoc.id <> -1 then xmldom.freedocument(domdoc) ;
    end if ;
    RAISE ;
    END ;
    However, after about 2000 of nodes lists parsed, I get an ArrayIndexOutOfBoundsException from XMLNodeCover. Obviously, I should release the nodes or the nodelist, but I have not found any procedure to do this.
    Pascal

  • XML Parser - Reading an XML document into the DocumentObject

    Hi guys,
    I have been trying to read an XML file and feed it into the XMLParser.
    I have read about the DOM API, and i can work with the DOM API in java
    scripts. How
    will i play with it in TOOL implementation of DOM API. Can anyone guide me
    in this
    process.
    Thanks for your help.
    Laks

    Sorry for this post, here ist the complete text.
    Is it possible to create a XML Parser (javax.xml.parsers.SaxParser or javax.xml.parsers.DocumentBuilder) which reads from a ByteChannel?
    Example:
    java.nio.channels.FileChannel fc = new ...;
    javax.xml.parsers.SaxParser parser = ...;
    org.xml.sax.HandlerBase hb = ...;
    parser.parse( fc, hb );

  • I want to create a parser file which dynamically reads out XML file.

    HI ,.
    I created a DOM parser where i am getting the values of XML file by tag names...
    which is increasing my code lines number ...
    So can any one suggest me with proper way of approach to overcome this....

    HI ...
    Here is the code...
    import java.io.ByteArrayOutputStream;
    import java.io.File;
    import java.io.PrintStream;
    import java.lang.Integer;
    import org.w3c.dom.*;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.DocumentBuilder;
    import org.xml.sax.SAXException;
    import org.xml.sax.SAXParseException;
    import sun.java2d.loops.FillPath;
    import sun.nio.ch.FileKey;
    public class XMLFileParser{
         int Size,Height,X,Y,W,H;
         String L;
         String Path;
         boolean resize;
         XMLFileParser(){
    void Parser(){
         try {
                DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
                Document doc = docBuilder.parse (new File("book.xml"));
                // normalize text representation
                doc.getDocumentElement ().normalize ();
                System.out.println ("Root element of the doc is " +
                     doc.getDocumentElement().getNodeName());
           //first node.
                                        NodeList FrameValues = doc.getElementsByTagName("Frame");
                                        NodeList children=(NodeList)doc.getDocumentElement().getChildNodes();
                                        System.out.println("total of childs are: "+children.getLength());
                                        //for (int j = 0; j < children.getLength(); j++)
                                        //     System.out.println(" the childs are: "+children.item(j));
                                             for(int s=0; s<FrameValues.getLength() ; s++){
                                                  // System.out.println(FrameValues.getLength());
                                 Node FirstFileNode = FrameValues.item(s);
                                 if(FirstFileNode.getNodeType() == Node.ELEMENT_NODE){
                                 Element frameelements = (Element)FirstFileNode;
                                 NodeList FrameValueList1 = frameelements.getElementsByTagName("setSize");
                                 Element firstAttributeElement = (Element)FrameValueList1.item(0);
                                    NodeList List1 = firstAttributeElement.getChildNodes();
                                 Node node1 = (Node)List1.item(0);
                                 String nodeName1 = node1.getNodeValue();
                                 int value1 = Integer.parseInt(nodeName1);                           
                                 setSize(value1);
                                 NodeList FrameValueList2 = frameelements.getElementsByTagName("Height");
                                 Element secondAttributeElement = (Element)FrameValueList2.item(0);
                                 NodeList List2 = secondAttributeElement.getChildNodes();
                                 Node node2 = (Node)List2.item(0);
                                 String nodeName2 = node2.getNodeValue();
                                 int value2 = Integer.parseInt(nodeName2);
                                   setHeight(value2);
                                 NodeList FrameValueList3 = frameelements.getElementsByTagName("BoundsX");
                                 Element thirdAttributeElement = (Element)FrameValueList3.item(0);
                                 NodeList List3 = thirdAttributeElement.getChildNodes();
                                 Node node3 = (Node)List3.item(0);
                                 String nodeName3 = node3.getNodeValue();
                                 int value3 = Integer.parseInt(nodeName3);
                                   setBounds(value3);
                                    NodeList FrameValueList4 = frameelements.getElementsByTagName("BoundsY");
                                    Element fourthAttributeElement = (Element)FrameValueList4.item(0);
                                    NodeList List4 = fourthAttributeElement.getChildNodes();
                                    Node node4 = (Node)List4.item(0);
                                    String nodeName4= node4.getNodeValue();
                                    int value4 = Integer.parseInt(nodeName4);
                                  setBounds1(value4);
                                  NodeList FrameValueList5 = frameelements.getElementsByTagName("BoundsW");
                                    Element fifthAttributeElement = (Element)FrameValueList5.item(0);
                                    NodeList List5 = fourthAttributeElement.getChildNodes();
                                    Node node5 = (Node)List5.item(0);
                                    String nodeName5 = node5.getNodeValue();
                                    int value5 = Integer.parseInt(nodeName5);
                                  setBounds2(value5);
                                  NodeList FrameValueList6 = frameelements.getElementsByTagName("BoundsH");
                                    Element sixthAttributeElement = (Element)FrameValueList6.item(0);
                                    NodeList List6 = sixthAttributeElement.getChildNodes();
                                    Node node6 = (Node)List6.item(0);
                                    String nodeName6 = node6.getNodeValue();
                                    int value6 = Integer.parseInt(nodeName6);
                                  setBounds3(value6);
                                  NodeList FrameValueList7 = frameelements.getElementsByTagName("Resize");
                                    Element seventhAttributeElement = (Element)FrameValueList6.item(0);
                                    NodeList List7 = seventhAttributeElement.getChildNodes();
                                    Node node7 = (Node)List7.item(0);
                                    String nodeName7 = node7.getNodeValue();
                                    boolean value7= Boolean.parseBoolean(nodeName7);
                                  setResize(value7);
         // second node.
                                        NodeList PanelValues = doc.getElementsByTagName("Panel");
                                        for(int s=0; s<PanelValues.getLength() ; s++){
                          // System.out.println(FrameValues.getLength());
                                 Node FirstFileNode = PanelValues.item(s);
                                 if(FirstFileNode.getNodeType() == Node.ELEMENT_NODE){
                                 Element Panelelements = (Element)FirstFileNode;
                                 NodeList PanelValueList1 = Panelelements.getElementsByTagName("Layout");
                                 Element firstAttributeElement = (Element)PanelValueList1.item(0);
                                    NodeList List1 = firstAttributeElement.getChildNodes();
                                 Node node1 = (Node)List1.item(0);
                                 String Layout = node1.getNodeValue();
                                 //int value1 = Integer.parseInt(nodeName1);                           
                                 setLayout(Layout);
                                 NodeList PanelValueList2 = Panelelements.getElementsByTagName("ImagePath");
                                 Element secondAttributeElement = (Element)PanelValueList2.item(0);
                                    NodeList List2 = secondAttributeElement.getChildNodes();
                                 Node node2 = (Node)List1.item(0);
                                 String path = node1.getNodeValue();
                                 //int value1 = Integer.parseInt(nodeName1);                           
                                 setPath(path);
                    }//end of if clause
                }//end of for loop with s1 var*/
            catch (SAXParseException err)
            System.out.println ("** Parsing error" + ", line "
                 + err.getLineNumber () + ", uri " + err.getSystemId ());
            System.out.println(" " + err.getMessage ());
            catch (SAXException e)
            Exception x = e.getException ();
            ((x == null) ? e : x).printStackTrace ();
            catch (Throwable t)
            t.printStackTrace ();
    private void setResize(boolean value7) {
         // TODO Auto-generated method stub
         resize=value7;
    public boolean getResize(){
         System.out.println("Resize" + resize);
         return resize;
    private void setPath(String path) {
         // TODO Auto-generated method stub
          Path = path;
    public String getPath(){
         System.out.println("Path" + Path);
         return Path;
    private void setLayout(String layout) {
         // TODO Auto-generated method stub
         L=layout;
    public String getLayout(){
         System.out.println("Layout" + L);
         return L;
    private void setBounds3(int value6) {
         // TODO Auto-generated method stub
         H=value6;
         System.out.println("setBoundsH" + H);
    public int getBounds3(){
         System.out.println("getBoundsH" + H);
         return H;
    private void setBounds2(int value5) {
         // TODO Auto-generated method stub
         W=value5;
         System.out.println("setBoundsW" + W);
    public int getBounds2(){
         System.out.println("getBoundsW" + W);
         return W;
    private void setBounds1(int value4) {
         // TODO Auto-generated method stub
         Y=value4;
         System.out.println("setBoundsY" + Y);
    public int getBounds1(){
         System.out.println("getBoundsY" + Y);
         return Y;
    public void setBounds(int value3) {
         // TODO Auto-generated method stub
    X= value3;
         System.out.println("setBoundsX" + X);
    public int getBounds(){
         System.out.println("getBoundsX" + X);
         return X ;
    public void setHeight(int value2) {
              // TODO Auto-generated method stub
              Height=value2;
              System.out.println("setHeight " + Height);
    public int getHeight(){
         System.out.println("getHeight " + Height);
         return (Height);
    setSize(int value1) {
              // TODO Auto-generated method stub
              Size=value1;
              System.out.println("setSize " + Size);
         public int getSize() {
              System.out.println("getSize " + Size);
              return ( Size);
          }here i am calling the elements of my xml file each time by tag name ...which is increasing my code lines....so any solution please....

  • Reading an xml file in actionscript using flex3

    plzz tell me how to read an xml file in actionscript using flex3.......

    One possible option to parse an xml-file to a flex XML object:
    public function parseConXML(source:String):void
                    xmlLoader = new URLLoader();
                    xmlLoader.load(new URLRequest(source));
                      // Eventlistener: if URL loaded --> onLoadComplete function
                      xmlLoader.addEventListener(Event.COMPLETE, xmlLoadComplete);
                public function xmlLoadComplete(evt:Event):void{               
                    var xml:XML = new XML();
                     // ignore comments in XML-File
                    XML.ignoreComments = true;  
                       //ignore whitespaces in XML-File
                     XML.ignoreWhitespace = true;
                    // XML-Objekt erstellen
                    xml = new XML(evt.target.data);
                   //AFTERWARDS use your xml as your wish

Maybe you are looking for