How to parsing xml data in sql statement??

Hi friends, I have a table which contain column as clob ,stores in xml format, for example my column contain xml data like this
<Employees xmlns="http://TargetNamespace.com/read_emp">
   <C1>106</C1>
   <C2>Harish</C2>
   <C3>1998-05-12</C3>
   <C4>HR</C4>
   <C5>1600</C5>
   <C6>10</C6>
</Employees>
  Then how to extract the data in above xml column data using SQL statement...

Duplicate post
How to parsing xml data in sql statement??

Similar Messages

  • How to parse xml data into java component

    hi
    everybody.
    i am new with XML, and i am trying to parse xml data into a java application.
    can anybody guide me how to do it.
    the following is my file.
    //MyLogin.java
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.*;
    class MyLogin extends JFrame implements ActionListener
         JFrame loginframe;
         JLabel labelname;
         JLabel labelpassword;
         JTextField textname;
         JPasswordField textpassword;
         JButton okbutton;
         String name = "";
         FileOutputStream out;
         PrintStream p;
         Date date;
         GregorianCalendar gcal;
         GridBagLayout gl;
         GridBagConstraints gbc;
         public MyLogin()
              loginframe = new JFrame("Login");
              gl = new GridBagLayout();
              gbc = new GridBagConstraints();
              labelname = new JLabel("User");
              labelpassword = new JLabel("Password");
              textname = new JTextField("",9);
              textpassword = new JPasswordField(5);
              okbutton = new JButton("OK");
              gbc.anchor = GridBagConstraints.NORTHWEST;
              gbc.gridx = 1;
              gbc.gridy = 5;
              gl.setConstraints(labelname,gbc);
              gbc.anchor = GridBagConstraints.NORTHWEST;
              gbc.gridx = 2;
              gbc.gridy = 5;
              gl.setConstraints(textname,gbc);
              gbc.anchor = GridBagConstraints.NORTHWEST;
              gbc.gridx = 1;
              gbc.gridy = 10;
              gl.setConstraints(labelpassword,gbc);
              gbc.anchor = GridBagConstraints.NORTHWEST;
              gbc.gridx = 2;
              gbc.gridy = 10;
              gl.setConstraints(textpassword,gbc);
              gbc.anchor = GridBagConstraints.NORTHWEST;
              gbc.gridx = 1;
              gbc.gridy = 15;
              gl.setConstraints(okbutton,gbc);
              Container contentpane = getContentPane();
              loginframe.setContentPane(contentpane);
              contentpane.setLayout(gl);
              contentpane.add(labelname);
              contentpane.add(labelpassword);
              contentpane.add(textname);
              contentpane.add(textpassword);
              contentpane.add(okbutton);
              okbutton.addActionListener(this);
              loginframe.setSize(300,300);
              loginframe.setVisible(true);
         public static void main(String a[])
              new MyLogin();
         public void reset()
              textname.setText("");
              textpassword.setText("");
         public void run()
              try
                   String text = textname.getText();
                   String blank="";
                   if(text.equals(blank))
                      System.out.println("First Enter a UserName");
                   else
                        if(text != blank)
                             date = new Date();
                             gcal = new GregorianCalendar();
                             gcal.setTime(date);
                             out = new FileOutputStream("log.txt",true);
                             p = new PrintStream( out );
                             name = textname.getText();
                             String entry = "UserName:- " + name + " Logged in:- " + gcal.get(Calendar.HOUR) + ":" + gcal.get(Calendar.MINUTE) + " Date:- " + gcal.get(Calendar.DATE) + "/" + gcal.get(Calendar.MONTH) + "/" + gcal.get(Calendar.YEAR);
                             p.println(entry);
                             System.out.println("Record Saved");
                             reset();
                             p.close();
              catch (IOException e)
                   System.err.println("Error writing to file");
         public void actionPerformed(ActionEvent ae)
              String str = ae.getActionCommand();
              if(str.equals("OK"))
                   run();
                   //loginframe.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    }

    hi, thanks for ur reply.
    i visited that url, i was able to know much about xml.
    so now my requirement is DOM.
    but i dont know how to code in my existing file.
    means i want to know what to link all my textfield to xml file.
    can u please help me out. i am confused.
    waiting for ur reply

  • How to Parse XML data directly from context variables in webdynpro

    Hello,
       I have two requirements:
    1) I have a context variable which has string value.
       I want to write the this value into a flat file.
       How do I do this in WebDynpro.
       Any sample code for this.
    2) In Webdynpro, I want to parse and process the XML data directly from a string context variable which
       has the value in XML format.
       How do I achieve this. Any pointers or sample codes for this.
    Thanks and Regards,
    Anupama.

    Anupama,
    Here is some link which talks about unpacking xml and converting to HTML.
    <a href="http://help.sap.com/saphelp_nw04/helpdata/en/eb/3dfb402eb5f76fe10000000a1550b0/content.htm">http://help.sap.com/saphelp_nw04/helpdata/en/eb/3dfb402eb5f76fe10000000a1550b0/content.htm</a>
    I have done something like this in portal development and not in webdynpro.But in principle it should work very where.

  • How to load XML data by sql*loader

    I want to use SQL*loader to load XML file, which was briefly mentioned in "Application Developer's
    Guide: XML" without any detail information and examples.
    Does anyone have the information including sample control file or know where I can get the info?
    Any help would be much appreciated.
    Thanks.
    Yi Zhong

    Yi,
    I found this on Meta-Link. Maybe this is it?
    goal: How to load a XML document into XMLType data type?
    fact: Oracle XML Developers Kit
    fact: Oracle Server - Enterprise Edition
    fact: SQL*Loader
    fix:
    The document can be loaded by SQL*Loader as if it was LOB data.
    The following example (Unix commands) demonstrates how to do this:
    $ ORACLE_SID=v901; export ORACLE_SID
    $ ORAENV_ASK=NO; export ORAENV_ASK
    $ . oraenv
    $ sqlplus /nolog <<EOF
    connect / as sysdba
    drop user oss120517 cascade;
    create user oss120517 identified by oss120517
    default tablespace users temporary tablespace temp
    quota unlimited on users;
    grant connect,resource to oss120517;
    revoke unlimited tablespace from oss120517;
    connect oss120517/oss120517
    create table test
    (xml_id number
    ,xml_doc sys.xmltype);
    EOF
    $ cat <<EOF > sqlload.ctl
    load data
    infile *
    into table test append
    fields terminated by ','
    (xml_id integer
    ,xml_filler filler char
    ,xml_doc lobfile(xml_filler) terminated by EOF)
    begindata
    1 , test.xml
    EOF
    $ sqlldr oss120517/oss120517 control=sqlload.ctl

  • Compare date in SQL statement

    yup.. how can i compare date in SQL statement??
    pls give me a completed example.

    I'd think this is a formatting problem. Why not try:
    PreparedStatement ps = myConnection.prepareStatement(
    "SELECT * FROM Receipt WHERE to_date(Date) > ? ");
    ps.setDate(1,TodayDate);
    ResultSet rs = ps.executeQuery();
    HTH,
    Ken

  • 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 store xml data into file in xml format through java program?

    HI Friends,
    Please let me know
    How to store xml data into file in xml format through java program?
    thanks......
    can discuss further at messenger.....
    Avanish Kumar Singh
    Software Engineer,
    Samsung India Development Center,
    Bangalore--560001.
    [email protected]

    Hi i need to write the data from an XML file to a Microsoft SQL SErver database!
    i got a piece of code from the net which allows me to parse th file:
    import java.io.IOException;
    import org.xml.sax.*;
    import org.xml.sax.helpers.*;
    import org.apache.xerces.parsers.SAXParser;
    import java.lang.*;
    public class MySaxParser extends DefaultHandler
    private static int INDENT = 4;
    private static String attList = "";
    public static void main(String[] argv)
    if (argv.length != 1)
    System.out.println("Usage: java MySaxParser [URI]");
    System.exit(0);
    String uri = argv[0];
    try
    XMLReader parser = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
    MySaxParser MySaxParserInstance = new MySaxParser();
    parser.setContentHandler(MySaxParserInstance);
    parser.parse(uri);
    catch(IOException ioe)
    ioe.printStackTrace();
    catch(SAXException saxe)
    saxe.printStackTrace();
    private int idx = 0;
    public void characters(char[] ch, int start, int length)
    throws SAXException
    String s = new String(ch, start, length);
    if (ch[0] == '\n')
    return;
    System.out.println(getIndent() + " Value: " + s);
    public void endDocument() throws SAXException
    idx -= INDENT;
    public void endElement(String uri, String localName, String qName) throws SAXException
    if (!attList.equals(""))
    System.out.println(getIndent() + " Attributes: " + attList);
    attList = "";
    System.out.println(getIndent() + "end document");
    idx -= INDENT;
    public void startDocument() throws SAXException
    idx += INDENT;
    public void startElement(String uri,
    String localName,
    String qName,
    Attributes attributes) throws SAXException
    idx += INDENT;
    System.out.println('\n' + getIndent() + "start element: " + localName);
    if (localName.compareTo("Machine") == 0)
    System.out.println("YES");
    if (attributes.getLength() > 0)
    idx += INDENT;
    for (int i = 0; i < attributes.getLength(); i++)
    attList = attList + attributes.getLocalName(i) + " = " + attributes.getValue(i);
    if (i < (attributes.getLength() - 1))
    attList = attList + ", ";
    idx-= INDENT;
    private String getIndent()
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < idx; i++)
    sb.append(" ");
    return sb.toString();
    }// END PRGM
    Now , am not a very good Java DEv. and i need to find a soln. to this prob within 1 week.
    The next step is to write the data to the DB.
    Am sending an example of my file:
    <Start>
    <Machine>
    <Hostname> IPCServer </Hostname>
    <HostID> 80c04499 </HostID>
    <MachineType> sun4u [ID 466748 kern.info] Sun Ultra 5/10 UPA/PCI (UltraSPARC-IIi 360MHz) </MachineType>
    <CPU> UltraSPARC-IIi at 360 MHz </CPU>
    <Memory> RAM : 512 MB </Memory>
    <HostAdapter>
    <HA> kern.info] </HA>
    </HostAdapter>
    <Harddisks>
    <HD>
    <HD1> c0t0d0 ctrl kern.info] target 0 lun 0 </HD1>
    <HD2> ST38420A 8.2 GB </HD2>
    </HD>
    </Harddisks>
    <GraphicCard> m64B : PCI PGX 8-bit +Accel. </GraphicCard>
    <NetworkType> hme0 : Fast-Ethernet </NetworkType>
    <EthernetAddress> 09:00:30:C1:34:90 </EthernetAddress>
    <IPAddress> 149.51.23.140 </IPAddress>
    </Machine>
    </Start>
    Note that i can have more than 1 machines (meaning that i have to loop thru the file to be able to write to the DB)
    Cal u tellme what to do!
    Even better- do u have a piece of code that will help me understand and implement the database writing portion?
    I badly need help here.
    THANX

  • Script for parsing xml data and inserting in DB

    Thank you for reading.
    I have the following example XML in an XML file. I need to write a script that can insert this data into an Oracle table. The table does not have primary keys. The data just needs to be inserted.
    I do not have xsd file in this scenario. Please suggest how to modify Method 1 https://community.oracle.com/thread/1115266?tstart=0 mentioned so that I can call the XML mentioned below and insert into a table
    Method 1
    Create or replace procedure parse_xml is 
      l_bfile   BFILE; 
      l_clob    CLOB; 
      l_parser  dbms_xmlparser.Parser; 
      l_doc     dbms_xmldom.DOMDocument; 
      l_nl      dbms_xmldom.DOMNodeList; 
      l_n       dbms_xmldom.DOMNode; 
      l_file      dbms_xmldom.DOMNodeList; 
      l_filen       dbms_xmldom.DOMNode; 
      lv_value VARCHAR2(1000); 
       l_ch      dbms_xmldom.DOMNode; 
    l_partname varchar2(100); 
    l_filename varchar2(1000); 
      l_temp    VARCHAR2(1000); 
      TYPE tab_type IS TABLE OF tab_software_parts%ROWTYPE; 
      t_tab  tab_type := tab_type(); 
    BEGIN 
      l_bfile := BFileName('DIR1', 'SoftwareParts.xml'); 
      dbms_lob.createtemporary(l_clob, cache=>FALSE); 
      dbms_lob.open(l_bfile, dbms_lob.lob_readonly); 
      dbms_lob.loadFromFile(dest_lob => l_clob,    src_lob  => l_bfile,    amount   => dbms_lob.getLength(l_bfile)); 
      dbms_lob.close(l_bfile);  
      dbms_session.set_nls('NLS_DATE_FORMAT','''DD-MON-YYYY'''); 
      l_parser := dbms_xmlparser.newParser; 
      dbms_xmlparser.parseClob(l_parser, l_clob); 
      l_doc := dbms_xmlparser.getDocument(l_parser); 
        dbms_lob.freetemporary(l_clob); 
      dbms_xmlparser.freeParser(l_parser); 
      l_nl := dbms_xslprocessor.selectNodes(dbms_xmldom.makeNode(l_doc),'/PartDetails/Part'); 
        FOR cur_emp IN 0 .. dbms_xmldom.getLength(l_nl) - 1 LOOP 
        l_n := dbms_xmldom.item(l_nl, cur_emp); 
        t_tab.extend; 
        dbms_xslprocessor.valueOf(l_n,'Name/text()',l_partname); 
        t_tab(t_tab.last).partname := l_partname; 
        l_file := dbms_xslprocessor.selectNodes(l_n,'Files/FileName'); 
        FOR cur_ch IN 0 .. dbms_xmldom.getLength(l_file) - 1 LOOP 
          l_ch := dbms_xmldom.item(l_file, cur_ch); 
          lv_value := dbms_xmldom.getnodevalue(dbms_xmldom.getfirstchild(l_ch)); 
          if t_tab(t_tab.last).partname is null then t_tab(t_tab.last).partname := l_partname; end if; 
          t_tab(t_tab.last).filename := lv_value; 
        t_tab.extend; 
       END LOOP; 
       END LOOP; 
        t_tab.delete(t_tab.last); 
      FOR cur_emp IN t_tab.first .. t_tab.last LOOP 
      if t_tab(cur_emp).partname is not null and  t_tab(cur_emp).filename is not null then 
        INSERT INTO tab_software_parts 
        VALUES 
        (t_tab(cur_emp).partname, t_tab(cur_emp).filename); 
        end if; 
      END LOOP; 
      COMMIT; 
      dbms_xmldom.freeDocument(l_doc); 
    EXCEPTION 
      WHEN OTHERS THEN 
        dbms_lob.freetemporary(l_clob); 
        dbms_xmlparser.freeParser(l_parser); 
        dbms_xmldom.freeDocument(l_doc); 
    END; 
    <TWObject className="TWObject">
      <array size="240">
        <item>
          <variable type="QuestionDetail">
            <questionId type="String"><![CDATA[30]]></questionId>
            <questionType type="questionType"><![CDATA[COUNTRY]]></questionType>
            <country type="String"><![CDATA[GB]]></country>
            <questionText type="String"><![CDATA[Please indicate]]></questionText>
            <optionType type="String"><![CDATA[RadioButton]]></optionType>
            <answerOptions type="String[]">
              <item><![CDATA[Yes]]></item>
              <item><![CDATA[No]]></item>
            </answerOptions>
            <ruleId type="String"><![CDATA[CRP_GB001]]></ruleId>
            <parentQuestionId type="String"></parentQuestionId>
            <parentQuestionResp type="String"></parentQuestionResp>
          </variable>
        </item>
        <item>
          <variable type="QuestionDetail">
            <questionId type="String"><![CDATA[40]]></questionId>
            <questionType type="questionType"><![CDATA[COUNTRY]]></questionType>
            <country type="String"><![CDATA[DE]]></country>
            <questionText type="String"><![CDATA[Please indicate]]></questionText>
            <optionType type="String"><![CDATA[RadioButton]]></optionType>
            <answerOptions type="String[]">
              <item><![CDATA[Yes]]></item>
              <item><![CDATA[No]]></item>
            </answerOptions>
            <ruleId type="String"><![CDATA[CRP_Q0001]]></ruleId>
            <parentQuestionId type="String"></parentQuestionId>
            <parentQuestionResp type="String"></parentQuestionResp>
          </variable>
        </item>
      </array>
    </TWObject>

    Reposted as
    Script to parse XML data into Oracle DB

  • How to parse XML for internal table

    hi guys, I would like to know how to parse xml for an internal table. I explain myself.
    Let's say you have a purchase order form where you have header data & items data. In my interactive form, the user can change the purchase order quantity at the item level. When I received back the pdf completed by mail, I need to parse the xml and get the po qty that has been entered.
    This is how I do to get header data from my form
    lr_ixml_node = lr_ixml_document->find_from_name( name = ''EBELN ).
    lv_ebeln = lr_ixml_node->get_value( ).
    How do we do to get the table body??
    Should I used the same method (find_from_name) and passing the depth parameter inside a do/enddo?
    thanks
    Alexandre Giguere

    Alexandre,
    Here is an example. Suppose your internal table is called 'ITEMS'.
    lr_node = lr_document->find_from_name('ITEMS').
    lv_num_of_children = lr_node->num_children( ).
    lr_nodechild = lr_node->get_first_child( ).
    do lv_num_of_children times.
        lv_num_of_attributes = lr_nodechild->num_children( ).
        lr_childchild = lr_nodechild->get_first_child( ).
       do lv_num_of_attributes times.
          lv_value = lr_childchild->get_value( ).
          case sy-index.
             when 1.
               wa_item-field1 = lv_value
             when 2.
               wa_item-field2 = lv_value.
          endcase.
          lr_childchild = lr_childchild->get_next( ).
       enddo.
       append wa_item to lt_item.
       lr_nodechild = lr_nodechild->get_next( ).
    enddo.

  • How to parse XML against XSD,DTD, etc.. locally (no internet connection) ?

    i've searched on how to parse xml against xsd,dtd,etc.. without the needs of internet connection..
    but unfortunately, only the xsd file can be set locally and still there needs the internet connection for the other features, properties.
    XML: GML file input from gui
    XSD: input from gui
    javax.xml
    package demo;
    import java.io.File;
    import java.io.IOException;
    import java.net.MalformedURLException;
    import java.net.URL;
    import javax.xml.XMLConstants;
    import javax.xml.transform.Source;
    import javax.xml.transform.stream.StreamSource;
    import javax.xml.validation.Schema;
    import javax.xml.validation.SchemaFactory;
    import javax.xml.validation.Validator;
    import org.xml.sax.SAXException;
    public class Sample1WithJavaxXML {
         public static void main(String[] args) {
              URL schemaFile = null;
              try {
                   //schemaFile = new URL("http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd");
                   File file0 = new File("AppSchema-C01-v1_0.xsd");
                   schemaFile = new URL(file0.toURI().toString());
              } catch (MalformedURLException e1) {
                   // TODO Auto-generated catch block
                   e1.printStackTrace();
              //Source xmlFile = new StreamSource(new File("web.xml"));
              Source xmlFile = new StreamSource(new File("C01.xml"));
              SchemaFactory schemaFactory = SchemaFactory
                  .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
              //File file1 = new File("XMLSchema.dtd");
              //SchemaFactory schemaFactory = SchemaFactory
                   //.newInstance("javax.xml.validation.SchemaFactory:XMLSchema.dtd");
              Schema schema = null;
              try {
                   schema = schemaFactory.newSchema(schemaFile);
              } catch (SAXException e1) {
                   // TODO Auto-generated catch block
                   e1.printStackTrace();
              Validator validator = schema.newValidator();
              try {
                validator.validate(xmlFile);
                System.out.println(xmlFile.getSystemId() + " is valid");
              } catch (SAXException e) {
                System.out.println(xmlFile.getSystemId() + " is NOT valid");
                System.out.println("Reason: " + e.getLocalizedMessage());
              } catch (IOException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
    }Xerces
    package demo;
    import java.io.File;
    import java.util.Date;
    import org.apache.xerces.parsers.DOMParser;
    public class SchemaTest {
         private String xmlFile = "";
         private String xsdFile = "";
         public SchemaTest(String xmlFile, String xsdFile) {
              this.xmlFile = xmlFile;
              this.xsdFile = xsdFile;
         public static void main (String args[]) {
              File file0 = new File("AppSchema-C01-v1_0.xsd");
              String xsd = file0.toURI().toString();
              SchemaTest testXml = new SchemaTest("C01.xml",xsd);
              testXml.process();
         public void process() {
              File docFile = new File(xmlFile);
              DOMParser parser = new DOMParser();
              try {
                   parser.setFeature("http://xml.org/sax/features/validation", true);
                   parser.setFeature("http://apache.org/xml/features/validation/schema", true);
                   parser.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation",
                             xsdFile);
                   ErrorChecker errors = new ErrorChecker();
                   parser.setErrorHandler(errors);
                   System.out.println(new Date().toString() + " START");
                   parser.parse(docFile.toString());
              } catch (Exception e) {
                   System.out.print("Problem parsing the file.");
                   System.out.println("Error: " + e);
                   System.out.println(new Date().toString() + " ERROR");
                   return;
              System.out.println(new Date().toString() + " END");
    }

    Thanks a lot Sir DrClap..
    I tried to use and implement the org.w3c.dom.ls.LSResourceResolver Interface which is based on the SAX2 EntityResolver.
    please give comments the way I implement it. Here's the code:
    LSResourceResolver Implementation
    import org.w3c.dom.ls.LSInput;
    import org.w3c.dom.ls.LSResourceResolver;
    import abc.xml.XsdConstant.Path.DTD;
    import abc.xml.XsdConstant.Path.XSD;
    public class LSResourceResolverImpl implements LSResourceResolver {
         public LSResourceResolverImpl() {
          * {@inheritDoc}
         @Override
         public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId, String baseURI) {
              ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
              LSInput input = new LSInputImpl(publicId, systemId, baseURI);
              if ("http://www.w3.org/2001/xml.xsd".equals(systemId)) {
                   input.setByteStream(classLoader.getResourceAsStream(XSD.XML));
              } else if (XsdConstant.PUBLIC_ID_XMLSCHEMA.equals(publicId)) {
                   input.setByteStream(classLoader.getResourceAsStream(DTD.XML_SCHEMA));
              } else if (XsdConstant.PUBLIC_ID_DATATYPES.equals(publicId)) {
                   input.setByteStream(classLoader.getResourceAsStream(DTD.DATATYPES));
              return input;
    }I also implement org.w3c.dom.ls.LSInput
    import java.io.InputStream;
    import java.io.Reader;
    import org.w3c.dom.ls.LSInput;
    public class LSInputImpl implements LSInput {
         private String publicId;
         private String systemId;
         private String baseURI;
         private InputStream byteStream;
         private String stringData;
         public LSInputImpl(String publicId, String systemId, String baseURI) {
              super();
              this.publicId = publicId;
              this.systemId = systemId;
              this.baseURI = baseURI;
         //getters & setters
    }Then, here's the usage/application:
    I create XMLChecker class (SchemaFactory implementation is Xerces)
    import java.io.File;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.List;
    import javax.xml.XMLConstants;
    import javax.xml.stream.FactoryConfigurationError;
    import javax.xml.transform.Source;
    import javax.xml.transform.stream.StreamSource;
    import javax.xml.validation.Schema;
    import javax.xml.validation.SchemaFactory;
    import javax.xml.validation.Validator;
    import org.xml.sax.ErrorHandler;
    import org.xml.sax.SAXException;
    import org.xml.sax.SAXParseException;
    import abc.xml.XsdConstant.Path.XSD;
    public class XMLChecker {
         private ErrorMessage errorMessage = new ErrorMessage();
         public boolean validate(String filePath){
              final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
              List<Source> schemas = new ArrayList<Source>();
              schemas.add(new StreamSource(classLoader.getResourceAsStream(XSD.XML_SCHEMA)));
              schemas.add(new StreamSource(classLoader.getResourceAsStream(XSD.XLINKS)));
              schemas.add(new StreamSource(classLoader.getResourceAsStream("abc/xml/AppSchema.xsd")));
              SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
              schemaFactory.setResourceResolver(new LSResourceResolverImpl());
              try {
                   Schema schema = schemaFactory.newSchema(schemas.toArray(new Source[schemas.size()]));
                   Validator validator = schema.newValidator();
                   validator.setErrorHandler(new ErrorHandler() {
                        @Override
                        public void error(SAXParseException e) throws SAXException {
                             errorMessage.setErrorMessage(e.getMessage());
                             errorMessage.setLineNumber(e.getLineNumber());
                             errorMessage.setColumnNumber(e.getLineNumber());
                             throw e;
                        @Override
                        public void fatalError(SAXParseException e) throws SAXException {
                             errorMessage.setErrorMessage(e.getMessage());
                             errorMessage.setLineNumber(e.getLineNumber());
                             errorMessage.setColumnNumber(e.getLineNumber());
                             throw e;
                        @Override
                        public void warning(SAXParseException e) throws SAXException {
                             errorMessage.setErrorMessage(e.getMessage());
                             errorMessage.setLineNumber(e.getLineNumber());
                             errorMessage.setColumnNumber(e.getLineNumber());
                             throw e;
                   StreamSource source = new StreamSource(new File(filePath));
                   validator.validate(source);
              } catch (SAXParseException e) {
                   return false;
              } catch (SAXException e) {
                   errorMessage.setErrorMessage(e.getMessage());
                   return false;
              } catch (FactoryConfigurationError e) {
                   errorMessage.setErrorMessage(e.getMessage());
                   return false;
              } catch (IOException e) {
                   errorMessage.setErrorMessage(e.getMessage());
                   return false;
              return true;
         public ErrorMessage getErrorMessage() {
              return errorMessage;
    }Edited by: erossy on Aug 31, 2010 1:56 AM

  • How to parse xml string

    Hi! I'm having problems parsing an xml string. I've done DOM and SAX parsing before. But both of them either parse a file or data from an input source. I don't think they handle strings. I also don't want to write the string into a file just so I can use DOM or SAX.
    I'm looking for something where I could simply do:
    Document doc = documentBuilder.parse( myXMLString );
    So the heirarchy is automatically established for me. Then I could just do
    Element elem = doc.getElement();
    String name = elem.getTagName();
    These aren't the only methods I would want to use. Again, my main problem is how to parse xml if it is stored in a string, not a file, nor comming from a stream.
    thanks!

    But both of them either parse a file or data from an input source. I don't think they handle strings.An InputSource can be constructed with a Reader as input. One useful subclass of Reader is StringReader, so you'd use something likeDocument doc = documentBuilder.parse(new InputSource(new StringReader(myXMLString)));

  • Parse XML in PL/SQL

    I need help with parsing xml data in PL/SQL. I was able to read the attribute name & values but not able to read the element text.Any help is greatly appreciated.Following is the anonymous block and the desired output -
    Declare
    nl xmldom.DOMNodeList;
    len1 number;
    len2 number;
    n xmldom.DOMNode;
    e xmldom.DOMElement;
    nnm xmldom.DOMNamedNodeMap;
    attrname varchar2(100);
    attrval varchar2(100);
    doc xmldom.DOMDocument;
    p xmlparser.Parser;
    in_xml clob;
    begin
    -- get all elements
    p := xmlparser.newParser;
    in_xml := '<?xml version="1.0" encoding="utf-8"?>
    <Issue>
    <T_ISSUE_TITLE ID = "1">Test Issue</T_ISSUE_TITLE>
    <T_ISSUE_DESC ID = "2">Update Test Issue</T_ISSUE_DESC>
    <STATUS ID = "3">2</STATUS>
    <ISSUE_SD ID = "4">07/09/10</ISSUE_SD>
    <ISSUE_ED ID = "5">09/09/10</ISSUE_ED>
    <CREATE_DT ID = "6">07/09/10</CREATE_DT>
    <CREATE_USER_ID ID = "7">John</CREATE_USER_ID>
    <LST_UPD_USER_ID ID = "8">John</LST_UPD_USER_ID>
    </Issue>';
    xmlparser.parseClob(p,in_xml);
    doc :=xmlparser.getDocument(p);
    nl := xmldom.getElementsByTagName(doc, '*');
    len1 := xmldom.getLength(nl);
    -- loop through elements
    for j in 0..len1-1 loop
    n := xmldom.item(nl, j);
    e := xmldom.makeElement(n);
    dbms_output.put_line(xmldom.getTagName(e) || ':');
    -- get all attributes of element
    nnm := xmldom.getAttributes(n);
    len2 := xmldom.getLength(nnm);
    if (xmldom.isNull(nnm) = FALSE) then
    len2 := xmldom.getLength(nnm);
    -- loop through attributes
    for i in 0..len2-1 loop
    n := xmldom.item(nnm, i);
    --dbms_output.put_line(n);
    attrname := xmldom.getNodeName(n);
    attrval := xmldom.getNodeValue(n);
    dbms_output.put_line(' ' || attrname || ' = ' || attrval);
    end loop;
    end if;
    end loop;
    end;
    /** Output
    Issue:
    T_ISSUE_TITLE:
    ID = 1, Test Issue
    T_ISSUE_DESC:
    ID = 2, Update Test Issue
    STATUS:
    ID = 3, 2
    ISSUE_SD:
    ID = 4, 07/09/10
    ISSUE_ED:
    ID = 5, 09/09/10
    CREATE_DT:
    ID = 6, 07/09/10
    CREATE_USER_ID:
    ID = 7, John
    LST_UPD_USER_ID:
    ID = 8, John
    Thank You.

    Use dbms_xslprocessor.valueOf and dbms_xmldom.getnodevalue to get the value of node
    eg: l_doc is paresed XML doc with nodes as partdetails and part
    declare
      l_n       dbms_xmldom.DOMNode;
      l_nl      dbms_xmldom.DOMNodeList;
    l_partname varchar2(100);
    begin
    ---parsing code--
    l_nl := dbms_xslprocessor.selectNodes(dbms_xmldom.makeNode(l_doc),'/PartDetails/Part');
    FOR cur_emp IN 0 .. dbms_xmldom.getLength(l_nl) - 1 LOOP
      l_n := dbms_xmldom.item(l_nl, cur_emp);
      dbms_xslprocessor.valueOf(l_n,'Name/text()',l_partname);
    dbms_output.put_line(l_partname);
    end loop;
    end;Edited by: SBH on Jul 13, 2010 11:06 AM

  • How to parse xml in sap abap

    Hello,
    Can anyone help me to know how to parse xml in sap abap.
    I have a xml file which i want to parse and store it in internal table.
    <?xml version="1.0" encoding="UTF-8"?>##<data><name>menaka<name></data>
    Regards,
    Menaka.H.B

    Hello,
    For how to get the node name, you have to refer to this :
    [https://wiki.sdn.sap.com/wiki/display/ABAP/Upload%20XML%20file%20to%20internal%20table|https://wiki.sdn.sap.com/wiki/display/ABAP/Upload%20XML%20file%20to%20internal%20table]
    Check the code after:
    WHEN if_ixml_node=>co_node_element
    It tells you how to get the node name.
    BR,
    Suhas

  • How to parse xml and import to execel

    pls let me know how to parse XML file and import all data to execel sheet.

    Hi Mandya,
    This is outside of the normal use case for TestStand. It would be best to use a code module (developed in LabVIEW, C, or any other language) to accomlish this and then call it from a step in TestStand. You can find examples on ActiveX here:
    http://forums.ni.com/t5/NI-TestStand/Controlling-Excel-from-TestStand-with-Activex-Automation/td-p/1...
    I hope this helps.
    Frank L.
    Software Product Manager
    National Instruments

  • How to load oracle data into SQL SERVER 2000?

    how to load oracle data into SQL SERVER 2000.
    IS THERE ANY UTILITY AVAILABLE?

    Not a concern for an Oracle forum.
    Als no need for SHOUTING.
    Conventional solutions are
    - dump the data to a csv file and load it in Mickeysoft SQL server
    - use Oracle Heterogeneous services
    - use Mickeysoft DTS
    Whatever you prefer.
    Sybrand Bakker
    Senior Oracle DBA

Maybe you are looking for

  • Is there any way to change the name of my home folder?

    It's called 'kristixhill' - I was recently married and want it renamed. Any suggestions?

  • Pairing Issues - Storm 1 and MacBook with 10.6.2

    I'm having trouble pairing my Storm with my MacBook (10.6.2).  My MacBook is discoverable and isn't found when I search from the phone.  When the phone is set to listen, I see the phone but can't get to the point where a passcode is generated.  It ge

  • Global counter Variable

    Hi All, I have a requirement where i hav to push 'n' no of files from n different senders(1 file each sender and each is a different scenario) to a same receiver. so, i have to name all the files at the receiving end with some counter. and that count

  • Creating a byte Array dynamically.Urgent Help needed.

    Hi there, I need to create a byte Array with the values derived from the array and then am passing this byte array to a method. Example : public static void main(String[] args) throws IOException { char chars[] = {'a','j','a','y'}; byte[] b = { (byte

  • Changing default ACL assignment

    What i've seen is that administrator users are created with a private ACL on all their oject and other users with a all published ACL. Now i'd like to create new user assigning them a different ACLPropertyBoundle by default. For expample i want to ha