How to parse XML document returned by webservices

Hi,
I have a form (version 10.1.2.0) which has to display the credit card types using webservices. I created the webstub and jar file through jdeveloper and then after adding the jar files in the respective classpaths, I import it in the forms. I write the code in when-button-pressed and it gives the result in xml document like this:
<?xml version="1.0" encoding="UTF-8"?><WSAnswerTO><error>false</error><errorMessage></errorMessage><
results><CardTypeTO><carTypId>3</carTypId><type>AMERICAN
EXPRESS</type><numLength>15</numLength><cvvLength>4</cvvLength><comments>1 800-639-0002</comments></CardTypeTO><CardTypeTO><carTypId>4</carTypId><type>DISCOVER</type><numLength>16</numLength><cvvLength>3</cvvLength><comments>1 800-347-2683</comments></CardTypeTO><CardTypeTO><carTypId>1</carTypId><type>MASTERCARD</type><numLength>16</numLength><cvvLength>3</cvvLength><comments>1 800-633-7367</comments></CardTypeTO><CardTypeTO><carTypId>2</carTypId><type>VISA</type><numLength>16</numLength><cvvLength>3</cvvLength><comments>1 800-945-2000</comments></CardTypeTO></results></WSAnswerTO>
From the above xml document, I only need to display the type (such as AMERICAN EXPRESS, VISA, ETC) in my forms. Can somebody please tell me how to do it. Do I need to store the values in a table first and then retrieve it. Please advise. I have already read a otn document in xml parsing but I didnt understand anything from it.
Please help. Thanks in advance.

Hello,
It probably exists a database package/function to parse this kind of stuff.
If you want to keep the process into the Forms, here is a PL/SQL package you can use:
CREATE OR REPLACE PACKAGE Pkg_Tools AS
  --  Types  --
  -- table of strings --
  TYPE TYP_TAB_CHAR IS TABLE OF VARCHAR2(4000) INDEX BY BINARY_INTEGER;
  --  Methodes   --
  -- function that return all contents for a given XML tag --
  FUNCTION Get_Xml_Tag
     PC$XmlContent  IN VARCHAR2,                 -- XML string
     PC$Tag         IN VARCHAR2,                 -- searched tag
     PC$NewLine     IN VARCHAR2 DEFAULT CHR(10)  -- defaull NL character
  RETURN TYP_TAB_CHAR ;
END Pkg_Tools;
CREATE OR REPLACE PACKAGE BODY Pkg_Tools
IS
  -- fonction de retour du contenu d'une balise XML  --
  FUNCTION Get_Xml_Tag
     PC$XmlContent  IN VARCHAR2,                 -- contenu XML
     PC$Tag         IN VARCHAR2,                 -- tag recherche
     PC$NewLine     IN VARCHAR2 DEFAULT CHR(10)  -- defaull NL character
  RETURN TYP_TAB_CHAR
  IS
   TC$Table      TYP_TAB_CHAR ;
   LC$Ligne      VARCHAR2(32000) ;
   LC$Xml        VARCHAR2(32000) ;
   LN$INDEX      PLS_INTEGER := 0 ;
   LN$TagDeb     PLS_INTEGER ;
   LN$TagFin     PLS_INTEGER ;
   LN$TagLength  PLS_INTEGER ;
   LN$LigLength  PLS_INTEGER ;
   LN$Occur      PLS_INTEGER := 1 ;
  BEGIN
    IF ( PC$XmlContent IS NOT NULL AND PC$Tag IS NOT NULL ) THEN
      LC$Xml := REPLACE( PC$XmlContent, CHR(13), '' ) ;
      LN$TagLength := LENGTH( PC$Tag ) ;
       LOOP
      LN$TagDeb := INSTR( LC$Xml, PC$Tag, 1, LN$Occur ) ;
      LN$TagFin := INSTR( LC$Xml, '</' || SUBSTR(PC$Tag,2, 256), 1, LN$Occur ) ;
      LN$LigLength := (LN$TagFin - ( LN$TagDeb + LN$TagLength ) ) ;
      IF (LN$TagDeb > 0 AND LN$TagFin > 0 ) THEN
         LN$Occur := LN$Occur + 1 ;
         LC$Ligne := SUBSTR( LC$Xml, LN$TagDeb + LN$TagLength, LN$LigLength ) ;
         LOOP
           LN$INDEX := LN$INDEX + 1 ;
           LN$TagDeb := INSTR( LC$Ligne, PC$NewLine ) ;
           IF LN$TagDeb > 0 THEN
             IF Trim( SUBSTR( LC$Ligne, 1, LN$TagDeb - 1 )) IS NOT NULL THEN
               TC$Table(LN$INDEX) := SUBSTR( LC$Ligne, 1, LN$TagDeb - 1 ) ;
             ELSE
               LN$INDEX := LN$INDEX - 1 ;
             END IF ;
             LC$Ligne := SUBSTR( LC$Ligne, LN$Tagdeb + LENGTH( PC$NewLine ), 30000 ) ;
           ELSE
             IF Trim(LC$Ligne) IS NOT NULL THEN
                TC$Table(LN$INDEX) := LC$Ligne ;
             END IF ;
             EXIT ;
           END IF ;
         END LOOP ;
      ELSE
          EXIT ;
      END IF ;
       END LOOP ;
    END IF ;
    RETURN TC$Table ;
  END Get_Xml_Tag ;
END Pkg_Tools;
/Then the call:
DECLARE
   LC$t  VARCHAR2(2000);
   LT$Table Pkg_Tools.TYP_TAB_CHAR ;
BEGIN
   lc$t := '<?xml version="1.0" encoding="UTF-8"?><WSAnswerTO><error>false</error><errorMessage></errorMessage><results>'
||'<CardTypeTO><carTypId>3</carTypId><TYPE>AMERICAN EXPRESS</TYPE><numLength>15</numLength><cvvLength>4</cvvLength>'
||'<comments>1 800-639-0002</comments></CardTypeTO><CardTypeTO><carTypId>4</carTypId><TYPE>DISCOVER</TYPE>'
||'<numLength>16</numLength><cvvLength>3</cvvLength><comments>1 800-347-2683</comments></CardTypeTO>'
||'<CardTypeTO><carTypId>1</carTypId><TYPE>MASTERCARD</TYPE><numLength>16</numLength><cvvLength>3</cvvLength>'
||'<comments>1 800-633-7367</comments></CardTypeTO><CardTypeTO><carTypId>2</carTypId><TYPE>VISA</TYPE>'
||'<numLength>16</numLength><cvvLength>3</cvvLength><comments>1 800-945-2000</comments></CardTypeTO></results></WSAnswerTO>' ;
   LT$Table := Pkg_Tools.Get_Xml_Tag(LC$T,'<TYPE>') ; 
   IF LT$Table.COUNT > 0 THEN
     FOR i IN LT$Table.First .. LT$Table.Last LOOP
        dbms_output.put_line( 'Table(' || i || ')=' || LT$Table(i) ) ;
     END LOOP ;
   ELSE
     dbms_output.put_line( 'tag xml not found' ) ;
   END IF ;
END;Francois

Similar Messages

  • How to parse XML document with default namespace with JDOM XPath

    Hi All,
    I am having difficulty parsing using Saxon and TagSoup parser on a namespace html document. The relevant content of this document are as follows:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    </head>
    <body>
        <div id="container">
            <div id="content">
                <table class="sresults">
                    <tr>
                        <td>
                            <a href="http://www.abc.com/areas" title="Hollywood, CA">hollywood</a>
                        </td>
                        <td>
                            <a href="http://www.abc.com/areas" title="San Jose, CA">san jose</a>
                        </td>
                        <td>
                            <a href="http://www.abc.com/areas" title="San Francisco, CA">san francisco</a>
                        </td>
                        <td>
                            <a href="http://www.abc.com/areas" title="San Diego, CA">San diego</a>
                        </td>
                  </tr>
    </body>
    </html>
    Below is the relevant code snippets illustrates how I have attempted to retrieve the contents (value of  <a>):
                 import java.util.*;
                 import org.jdom.*;
                 import org.jdom.xpath.*;
                 import org.saxpath.*;
                 import org.ccil.cowan.tagsoup.Parser;
    ( 1 )       frInHtml = new FileReader("C:\\Tmp\\ABC.html");
    ( 2 )       brInHtml = new BufferedReader(frInHtml);
    ( 3 ) //    SAXBuilder saxBuilder = new SAXBuilder("org.apache.xerces.parsers.SAXParser");
    ( 4 )       SAXBuilder saxBuilder = new SAXBuilder("org.ccil.cowan.tagsoup.Parser");
    ( 5 )       org.jdom.Document jdomDocument = saxbuilder.build(brInHtml);
    ( 6 )       XPath xpath =  XPath.newInstance("/ns:html/ns:body/ns:div[@id='container']/ns:div[@id='content']/ns:table[@class='sresults']/ns:tr/ns:td/ns:a");
    ( 7 )       xpath.addNamespace("ns", "http://www.w3.org/1999/xhtml");
    ( 8 )       java.util.List list = (java.util.List) (xpath.selectNodes(jdomDocument));
    ( 9 )       Iterator iterator = list.iterator();
    ( 10 )     while (iterator.hasNext())
    ( 11 )     {
    ( 12 )            Object object = iterator.next();
    ( 13 ) //         if (object instanceof Element)
    ( 14 ) //               System.out.println(((Element)object).getTextNormalize());
    ( 15 )             if (object instanceof Content)
    ( 16 )                   System.out.println(((Content)object).getValue());
    ….This program would work on the same document without the default namespace, hence, it would not be necessary to include “ns” prefix along in the XPath statements (line 6-7) either. Moreover, I was using “org.apache.xerces.parsers.SAXParser” to have successfully retrieve content of <a> from the same document without default namespace in the past.
    I would like to achieve the following objectives if possible:
    ( i ) Exclude DTD and namespace in order to simplifying the parsing process. How this could be done?
    ( ii ) If this is not possible, how to include it in XPath statements (line 6-7) so that the value of <a> is picked up correctly?
    ( iii ) Would changing from “org.apache.xerces.parsers.SAXParser” to “org.ccil.cowan.tagsoup.Parser” make any difference as far as using XPath is concerned?
    ( iv ) Failing to exlude DTD, how to change the lookup of a PUBLIC DTD to a local SYSTEM one and include a local DTD for reference?
    I am running JDK 1.6.0_06, Netbeans 6.1, JDOM 1.1, Saxon6-5-5, Tagsoup 1.2 on Windows XP platform.
    Any assistance would be appreciated.
    Thanks in advance,
    Jack

    Here's an example of using a custom EntityResolver with the standard DocumentBuilder provided by the JDK. The code may or may not be similar for the parsers that you're using.
    import java.io.IOException;
    import java.io.StringReader;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import org.w3c.dom.Document;
    import org.xml.sax.EntityResolver;
    import org.xml.sax.InputSource;
    import org.xml.sax.SAXException;
    public class ParseExamples
        private final static String COMMON_XML
            = "<music>"
            +     "<artist name=\"Anderson, Laurie\">"
            +         "<album>Big Science</album>"
            +         "<album>Strange Angels</album>"
            +     "</artist>"
            +     "<artist name=\"Fine Young Cannibals\">"
            +         "<album>The Raw & The Cooked</album>"
            +     "</artist>"
            + "</music>";
        private final static String COMMON_DTD
            = "<!ELEMENT music (artist*)>"
            + "<!ELEMENT artist (album+)>"
            + "<!ELEMENT album (#PCDATA)>"
            + "<!ATTLIST artist name CDATA #REQUIRED>";
        public static void main(String[] argv)
        throws Exception
            // this version uses just a SYSTEM identifier - note that it gets turned
            // into a file: URL
            String xml = "<!DOCTYPE music SYSTEM \"bar\">"
                       + COMMON_XML;
            // this version uses both PUBLIC and SYSTEM identifiers; the SYSTEM ID
            // gets munged, the PUBLIC ID doesn't
    //        String xml = "<!DOCTYPE music PUBLIC \"foo\" \"bar\">"
    //                   + COMMON_XML;
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            dbf.setValidating(true);
            DocumentBuilder db = dbf.newDocumentBuilder();
            db.setEntityResolver(new EntityResolver()
                public InputSource resolveEntity(String publicId, String systemId)
                    throws SAXException, IOException
                    System.out.println("publicId = " + publicId);
                    System.out.println("systemId = " + systemId);
                    return new InputSource(new StringReader(COMMON_DTD));
            Document dom = db.parse(new InputSource(new StringReader(xml)));
            System.out.println("root element name = " + dom.getDocumentElement().getNodeName());
    }

  • Newbee - How to parse XML document

    I need complete code to parse java. It can be using SAX or Xerces2. Any help would greatly be appreciated

    I need complete code to parse java. It can be using SAX or Xerces2. Any help would greatly be appreciated

  • 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

    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 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 document which have xlink/xpointer inside

    dear friends,
    There are lots of topic talking about parse xml, validating xml with schema and so on, but no one or any book talking about parsing xml document which can parse document with link inside.
    According to Mr Meggison at http://www.megginson.com/Background/
    we can do it, but he is not expert with this thing.
    For example I have 3 XML document. My main XML document, let named it A.XML have XPointer inside and this element pointing to B.XML and C.XML using xpointer. how to parse A.XML and in the same time my SAX recognized this XPointer and parse also element inside B.XML and C.XML.
    I am really grateull for any helpful information from you.
    best regards

    I think you need to look for a SAX or DOM parser that undestands XPointers and knows how to follow them to additional content.
    I have used XSLT and specified external documents to it. It knows how to read a document and in effect make a nodeset which can be searched with the XPath capabilities of XSLT.
    It sounds like you wnat an <include file="xxx"/> capability and have the parser stop reading the current file, and start reading the second file.
    That works in Schemas, but I'm unaware of any way to do it with SAX or DOM in one pass.
    It would not be too hard to process the first file, say with DOM.
    After the Document is built, go find the <include> elements, read get the attribute needed, build a new Document and merge it into the original Document in place of the <include> element.
    Is this more what you want to do?
    Dave Patterson

  • 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 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??

  • How to parse xml file in midlet

    Hi Guys,
    i wish to parse xml file and display it in my midlet. i found api's supporting xml parsing in j2se ie., in java.net or j2se 5.0. Can u please help me what package to use in midlet?
    how to parse xml info and display in midlet? Plz reply soon......Thanks in advance....

    i have exactly the same problem with KXml2, but using a j2me-polish netbeans project.
    i've tried to work around with similar ways like you, but none of them worked. now i've spent 3 days for solving this problem, i'm a bit disappointed :( what is wrong with setting the downloaded kxml2 jar path in libraries&resources?
    screenshot

  • 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 publish XML document whose source is stored in clob column

    I have to create simple application:
    in one table are stored some information about XML documents (date of creation, etc.) and the document source itself in one (unfortunatelly clob type) column.
    The point is to anable users finding document(s) and viewing it.
    Using forms I can search and display information about documents. But I have no idea how to publish XML document whose source is stored in clob column.
    I am using Oracle Portal 3.0 on NT.
    Thanks in advance.

    Hi Sergio,
    This link might be helpful:
    http://www.oracle.com/webfolder/technetwork/tutorials/obe/db/apex/r31/apex31nf/apex31blob.htm
    Also refer the BLOB Download Format Mask :
    {message:id=9716335}
    Here I have given the format mask for APEX 4.0, which will slightly differ for 3.2.1 and proposed changes
    in the format mask are:
    1) Format Mask: DOWNLOAD
    2) Content Disposition: Inline
    This will be achieved with it:
    >
    But now, my user would like to know if it´s possible that APEX application can OPEN some of these files stored on this BLOB column WITHOUT download it.
    My user would like to see a hiperlink (or button) that, if pressed/acessed, can open a new page (or a page inside application) with the document. He doesn´t need to edit this oppened file. He only wants to see it.
    >
    Hope it helps!
    Regards,
    Kiran

  • 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 ignore white space when parse xml document using xerces 2.4.0

    When I run the program with the xml given below the following error comes.
    Problem parsing the file.java.lang.NullPointerExceptionjava.lang.NullPointerExce
    ption
    at SchemaTest.main(SchemaTest.java:25)
    ============================================================
    My expectation is "RECEIPT". Pls send me the solution.
    import org.apache.xerces.parsers.DOMParser;
    import org.xml.sax.InputSource;
    import java.io.*;
    import org.xml.sax.ErrorHandler;
    import org.w3c.dom.*;
    public class SchemaTest {
    public static void main (String args[])
    try
    FileInputStream is = new FileInputStream(new File("C:\\ADL\\imsmanifest.xml"));
    InputSource in = new InputSource(is);
    DOMParser parser = new DOMParser();
    //parser.setFeature("http://xml.org/sax/features/validation", false);
    //parser.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation", "memory.xsd");
    //ErrorHandler errors = new ErrorHandler();
    //parser.setErrorHandler(errors);
    parser.parse(in);
    Document manifest = parser.getDocument();
    manifest.normalize();
    NodeList nl = manifest.getElementsByTagName("organization");
    System.out.println((((nl.item(0)).getChildNodes()).item(0)).getFirstChild().getNodeValue());
    catch (Exception e)
    System.out.print("Problem parsing the file."+e.toString());
    e.printStackTrace();
    <?xml version = '1.0'?>
    <organizations default="detail">
    <organization identifier="detail" isvisible="true">
    <title>RECEIPT</title>
    <item identifier="S100000" identifierref="R100000" isvisible="true">
    <title>Basic Module</title>
    <item identifier="S100001" identifierref="R100001" isvisible="true">
    <title>Objectives</title>
    <metadata/>
    </item>
    </item>
    <metadata/>
    </organization>
    </organizations>
    Is there a white space problem? How do I get rid from this problem.

    ok now i really wrote the whole code, a bit scrolling in the API is to hard?
                DocumentBuilderFactory dbf = new DocumentBuilderFactory();
                DocumentBuilder db = dbf.newDocumentBuilder();
                dbf.setNamespaceAware(true); //or set false
                Document d = db.parse(inputstream);

Maybe you are looking for

  • Multiple Partners for the same customer in Message tracking of SEEBURGER

    Hi, This is for third party customers which use EDI messages. We have for one customer multiple partner numbers configured in Partner profile. I would like to know while configuring the trading partners in SEEBURGER Message Tracking, can we have mult

  • Offline Navigation not working

    If my Nokia N9 is offline due to lack of coverage or in flight mode, the Drive nor the Maps Application can't find a route to a selected place. I have downloaded the maps, I even can find the address on the maps. But when I try to let N9 navigate to

  • Error 114   Cant save a pdf from the scanner

    Error 114   I can scan and creat a pdf but I cant save it. New HP ENVY printer / scanner working correctly otherwise.

  • Recommended throughput for Oracle data warehouse

    Hi, I know up front this is going to be a vague question...but I'm trying to determine approximate I/O bandwidth for a data mart server. Right now we're hosting 3 or 4 different marts on it, but that number is going to increase. Oracle's DW "2 day" c

  • Adding features to Windows Technical Preview

    Why serial code not work with Windows Technical Preview evalution copy Build 9879? Add features to Windows Technical Preview and asks for serial key, two different serial key but not work.