How to validate generated XML-Document in Memory by XML-Schema?

Hi all!
I have the following problem:
I am generating a Document using the DOM delivered with Xerces 2.6.2.
Before I'll send the generated xml-document through network to another system I have to check with my xml-schema if the document is correct.
In the DOM-FAQ I found an "example" trying to explain how it should work. But with this example the problems begin.
I am creating my document with this method:
     public void createDocument() {
          myDOM = DOMImplementationImpl.getDOMImplementation();
          doc = myDOM.createDocument("", "documentData", null);
          root = doc.getDocumentElement();
          root.setAttribute(
               "xmlns:xsi",
               "http://www.w3.org/2001/XMLSchema-instance");
          //          root.setAttribute("xsi:noNamespaceSchemaLocation", "myScheme.xsd");
          domConfig = ((DocumentImpl) doc).getDomConfig();
          domConfig.setParameter(
               "schema-location",
               "file:///d:/workspace/XMLProject/WebContent/WEB-INF/myScheme.xsd");
          domConfig.setParameter("error-handler", new EHandler());
          domConfig.setParameter("validate", Boolean.TRUE);
     }In the line getting the domConfig, it is getting differeing to the example: The example is like this:
import org.w3c.dom.Document;
import org.w3c.dom.DOMConfiguration;
import org.w3c.dom.ls.LSParser;
Document document = builder.parseURI("data/personal-schema.xml");
DOMConfiguration config = document.getConfig();
config.setParameter("error-handler",new MyErrorHandler());
config.setParameter("validate", Boolean.TRUE);
document.normalizeDocument();They get the DOM-Configuration from the document-Object, but my document-Object has no "getConfig()" and only after type-casting I get a getDomConfig()-Method to get the configuration.
Then I fill my document and call                
((DocumentImpl) doc).normalizeDocument();When I run my Application I get the following error:
org.w3c.dom.DOMException: FEATURE_NOT_SUPPORTED: The parameter schema-location is recognized but the requested value cannot be set.
     at org.apache.xerces.dom.DOMConfigurationImpl.setParameter(Unknown Source)
     at xmlProject.createDocument(Convert.java:63)
     at xmlProject.Convert.main(Convert.java:154)I tried several ways to get the validation without success.
The next question is how I should refer to my xml-schema (which path) and where to place it relative to my jar I will generate, because I will have no webserver I could place it on.
Has anyone any experience with validating a document created and not placed on disc?
I have also another question to SAX: I read, that it is reading a document without saving it in the memory. I think this means that if I am validating it by SAX it will be read once and for parsing it will be read a second time. If I would transfer the document over an tcp-connection, I only have the document once in my inputstream and after validation it would be consumed I think. But what can I parse then? Or did I missed a detail with the function of the SAX?
Thank you for your help!
Yours
Christian

static final String schemaSource = argv[0];
static final String JAXP_SCHEMA_SOURCE =
"http://java.sun.com/xml/jaxp/properties/schemaSource";
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
factory.setAttribute(JAXP_SCHEMA_SOURCE,
new File(schemaSource));

Similar Messages

  • Does unmarshall operation hold entire XML document in memory?

    Hi,
    When the unmarshall operation is done on a large XML file, does the root element Java object returned hold the entire XML document in memory? I have a large XML file that I want to unmarshall that contains many <product> elements for example. I want use up as less memory as possible. How would I achieve this?
    Thanks.

    Yes. I am going with Stax + JAXB to unmarshall. Stax so I could iterate over each element and then use JAXB to unmarshall an element at a time. But the solution is a bit involved. I wanted to do it with just JAXB and so I want to know if JAXB holds the entire content tree in memory if I unmarshall the root element.

  • In Reply to : How to validate org.jdom.Document object using xsd: dvohra09

    Hi All
    I am creating org.jdom.Document object using constructor Document() and adding children using setRootElement(), setChildren() and addContent() methods. The children are objects of org.jdom.Element. If i want to validate the org.jdom.Document using xsd what i have to do. Thanks in anticipation.

    I tried the below code and it is always giving the
    Parsing fatal error : The markup in the document preceding the root element must be well-formed.
    But it is possible to validate the same Document object as right document after writing it onto xml file using XMLOutputter and parsing it using DOMParser
    Thanks in anticipation
    org.jdom.Document document;
    String documentString=document.toString();
    StringReader stringReader=new
    StringReader(documentString);
    SAXBuilder saxBuilder =new
    SAXBuilder("org.apache.xerces.parsers.SAXParser",true);
    saxBuilder.setFeature("http://xml.org/sax/features/vali
    ation",  true);
    saxBuilder.setFeature("http://apache.org/xml/features/v
    lidation/schema",  true);
    saxBuilder.setFeature("http://apache.org/xml/features/v
    lidation/schema-full-checking", true);
    //Set a error handler with
    setErrorHandler(org.xml.sax.ErrorHandler errorHandler)
    saxBuilder.build(stringReader);

  • Problem when trying to load an XML document with DTD or XML SCHEMA

    Hello
    I have tried to load an XML document in Data Services, and I created the xsd file and Dtd file. (With altova xml spy software automatically) to import into SAP Data Services 3.2. .
    In Data Services I created the dtd import file DTD and then called the XML file from the DTD (the xml file is validated vs the dtd file), and I could not read the xml correctly because it tells me that an ELEMENT called <item> expected joiners who did not come in the structure of import (dtd), but if the xml.
    I understand that the document root is the label: CUSTOMER_FULL_2014, the data flow is as follows:CARGA_XML_CUSTOMER |
    Turns out the joiners element is used to separate the xml elements are repeated, but is used at different levels. My idea is that the design will dtd second, or something I'm missing or is incorrectly stated.
    Thank you.
    xml
    +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    <?xml version="1.0" encoding="utf-8"?>
    <CUSTOMER_FULL_2014>
      <item>
      <CUST_NO>202222</CUST_NO>
      <ADDRESS>
      <item>
      <SHIP_TO>202222</SHIP_TO>
      <NAME1>Henley.</NAME1>
      <STREET>Vitacura #40</STREET>
      <CITY>LIMA</CITY>
      </item>
      </ADDRESS>
      <EQUIPMENT>
      <item>
      <EQUI_NO>81623</EQUI_NO>
      </item>
      <item>
      <EQUI_NO>81633</EQUI_NO>
      </item>
      <item>
      <EQUI_NO>81993</EQUI_NO>
      </item>
      <item>
      <EQUI_NO>82003</EQUI_NO>
      </item>
      <item>
      <EQUI_NO>82013</EQUI_NO>
      </item>
      <item>
      <EQUI_NO>82103</EQUI_NO>
      </item>
      <item>
      <EQUI_NO>82113</EQUI_NO>
      </item>
      <item>
      <EQUI_NO>581203</EQUI_NO>
      </item>
      <item>
      <EQUI_NO>900003-EMER</EQUI_NO>
      </item>
      <item>
      <EQUI_NO>9000033-STOCK</EQUI_NO>
      </item>
      </EQUIPMENT>
      <STORAGE_LOC>
      <item>
      <STOR_LOC_NO>0001</STOR_LOC_NO>
      <DESCRIPTION>01 Parts Center</DESCRIPTION>
      </item>
      <item>
      <STOR_LOC_NO>0056</STOR_LOC_NO>
      <DESCRIPTION>56 henley</DESCRIPTION>
      </item>
      </STORAGE_LOC>
      </item>
      <item>
      <CUST_NO>2007933434343</CUST_NO>
      <ADDRESS>
      <item>
      <SHIP_TO>2007933434343</SHIP_TO>
      <NAME1>Campos de Almacenaje SA</NAME1>
      <STREET>Calacoto2, Calle 1</STREET>
      <HOUSE_NO>Piso 1</HOUSE_NO>
      <CITY>La Paz</CITY>
      </item>
      </ADDRESS>
      <EQUIPMENT>
      <item>
      <EQUI_NO>90000-EMER</EQUI_NO>
      </item>
      <item>
      <EQUI_NO>90000333-STOCK</EQUI_NO>
      </item>
      </EQUIPMENT>
      <STORAGE_LOC>
      <item>
      <STOR_LOC_NO>00012</STOR_LOC_NO>
      <DESCRIPTION>01 Parts Center</DESCRIPTION>
      </item>
      <item>
      <STOR_LOC_NO>0056</STOR_LOC_NO>
      <DESCRIPTION>56 henley</DESCRIPTION>
      </item>
      </STORAGE_LOC>
      </item>
      <item>
      <CUST_NO>200801333</CUST_NO>
      <ADDRESS>
      <item>
      <SHIP_TO>200801333</SHIP_TO>
      <NAME1>CONSTRUCTORA SA.</NAME1>
      <STREET>Ruta Panamericana Km 100</STREET>
      <CITY>San Antonio 23</CITY>
      </item>
      </ADDRESS>
      <EQUIPMENT>
      <item>
      <EQUI_NO>1507933</EQUI_NO>
      </item>
      <item>
      <EQUI_NO>1509733</EQUI_NO>
      </item>
      <item>
      <EQUI_NO>90000-EMER</EQUI_NO>
      </item>
      <item>
      <EQUI_NO>90000333-STOCK</EQUI_NO>
      </item>
      </EQUIPMENT>
      <STORAGE_LOC>
      <item>
      <STOR_LOC_NO>0001</STOR_LOC_NO>
      <DESCRIPTION>01 Parts Center</DESCRIPTION>
      </item>
      <item>
      <STOR_LOC_NO>0056</STOR_LOC_NO>
      <DESCRIPTION>56 henley</DESCRIPTION>
      </item>
      </STORAGE_LOC>
      </item>
    </CUSTOMER_FULL_2014>
    ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    ARCHIVO DTD CREADO (automáticamente con xml spy)
    <?xml version="1.0" encoding="UTF-8"?>
    <!-- DTD generado con XMLSpy v2014 rel. 2 (x64) (http://www.altova.com) -->
    <!ELEMENT CITY (#PCDATA)>
    <!ELEMENT item ((SHIP_TO, NAME1, STREET, HOUSE_NO?, CITY) | (CUST_NO, ADDRESS, EQUIPMENT, STORAGE_LOC) | (STOR_LOC_NO, DESCRIPTION) | EQUI_NO)>
    <!ELEMENT NAME1 (#PCDATA)>
    <!ELEMENT STREET (#PCDATA)>
    <!ELEMENT ADDRESS (item)>
    <!ELEMENT CUST_NO (#PCDATA)>
    <!ELEMENT EQUI_NO (#PCDATA)>
    <!ELEMENT SHIP_TO (#PCDATA)>
    <!ELEMENT HOUSE_NO (#PCDATA)>
    <!ELEMENT EQUIPMENT (item+)>
    <!ELEMENT DESCRIPTION (#PCDATA)>
    <!ELEMENT STORAGE_LOC (item+)>
    <!ELEMENT STOR_LOC_NO (#PCDATA)>
    <!ELEMENT CUSTOMER_FULL_2014 (item+)>
    ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    The error of MONITOR Data Services
    11676
    5184
    XML-240108
    11-04-2014 17:34:16
    |Data flow CARGA_XML_CUSTOMER|Reader READ MESSAGE customer OUTPUT(customer)
    11676
    5184
    XML-240108
    11-04-2014 17:34:16
    An element named <item> present in the XML data input does not exist in the XML format used to set up this XML source in data
    11676
    5184
    XML-240108
    11-04-2014 17:34:16
    flow <CARGA_XML_CUSTOMER>. Please validate your XML data.
    11676
    5184
    XML-240307
    11-04-2014 17:34:16
    |Data flow CARGA_XML_CUSTOMER|Reader READ MESSAGE customer OUTPUT(customer)
    11676
    5184
    XML-240307
    11-04-2014 17:34:16
    XML parser failed: See previously displayed error message.
    The Error from Monitor
    The metadata DTD
    Thanks
    Juan

    Hi Juan Juan,
    I generated a new XSD file using MS Visual Studio based on your XML file.
    The empty spaces in the source is replaced with <Null> in the target table.
    Here is the XSD:
    <?xml version="1.0" encoding="utf-8"?>
    <xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
        <xs:element name="CUSTOMER_FULL_20140207_033015_001">
            <xs:complexType>
                <xs:sequence>
                    <xs:choice maxOccurs="unbounded">
                        <xs:element name="CUST_NO" type="xs:unsignedInt" />
                        <xs:element name="ADDRESS">
                            <xs:complexType>
                                <xs:sequence>
                                    <xs:element name="SHIP_TO" type="xs:unsignedInt" />
                                    <xs:element name="NAME1" type="xs:string" />
                                    <xs:element name="STREET" type="xs:string" />
                                    <xs:element minOccurs="0" name="HOUSE_NO" type="xs:string" />
                                    <xs:element name="CITY" type="xs:string" />
                                </xs:sequence>
                            </xs:complexType>
                        </xs:element>
                        <xs:element name="EQUIPMENT">
                            <xs:complexType>
                                <xs:sequence>
                                    <xs:element maxOccurs="unbounded" name="EQUI_NO" type="xs:string" />
                                </xs:sequence>
                            </xs:complexType>
                        </xs:element>
                        <xs:element name="STORAGE_LOC">
                            <xs:complexType>
                                <xs:sequence>
                                    <xs:choice maxOccurs="unbounded">
                                        <xs:element name="STOR_LOC_NO" type="xs:unsignedByte" />
                                        <xs:element name="DESCRIPTION" type="xs:string" />
                                    </xs:choice>
                                </xs:sequence>
                            </xs:complexType>
                        </xs:element>
                    </xs:choice>
                </xs:sequence>
            </xs:complexType>
        </xs:element>
    </xs:schema>
    For Source XML
    <?xml version="1.0" encoding="utf-8"?>
    <CUSTOMER_FULL_20140207_033015_001>
      <CUST_NO>200530</CUST_NO>
      <ADDRESS>
      <SHIP_TO>903533</SHIP_TO>
      <NAME1>HENLEY - PART MAQUINARIAS S.A.</NAME1>
      <STREET>Dean Camilo # 148, San Carlos</STREET>
      <CITY>LIMA</CITY>
      </ADDRESS>
      <EQUIPMENT>
      <EQUI_NO>4442</EQUI_NO>
      <EQUI_NO>8163</EQUI_NO>
      <EQUI_NO>8199</EQUI_NO>
      <EQUI_NO>8200</EQUI_NO>
      <EQUI_NO>8201</EQUI_NO>
      <EQUI_NO>8210</EQUI_NO>
      <EQUI_NO>8211</EQUI_NO>
      <EQUI_NO>58120</EQUI_NO>
      <EQUI_NO>90000-EMERGENCY</EQUI_NO>
      <EQUI_NO>90000-STOCK</EQUI_NO>
      </EQUIPMENT>
      <STORAGE_LOC>
      <STOR_LOC_NO>0001</STOR_LOC_NO>
      <DESCRIPTION>01 Parts Center</DESCRIPTION>
      <STOR_LOC_NO>0056</STOR_LOC_NO>
      <DESCRIPTION>56 HEN</DESCRIPTION>
      </STORAGE_LOC>
      <CUST_NO>200793</CUST_NO>
      <ADDRESS>
      <SHIP_TO>200793</SHIP_TO>
      <NAME1>Minera San Cristobal S.A.</NAME1>
      <STREET>Calacoto, Calle 90, Torre 2</STREET>
      <HOUSE_NO>Piso 5</HOUSE_NO>
      <CITY>La Paz</CITY>
      </ADDRESS>
      <EQUIPMENT>
      <EQUI_NO>90000-EMERGENCY</EQUI_NO>
      <EQUI_NO>90000-STOCK</EQUI_NO>
      </EQUIPMENT>
      <STORAGE_LOC>
      <STOR_LOC_NO>0001</STOR_LOC_NO>
      <DESCRIPTION>01 Parts Center</DESCRIPTION>
      <STOR_LOC_NO>0056</STOR_LOC_NO>
      <DESCRIPTION>56 HEN</DESCRIPTION>
      </STORAGE_LOC>
      <CUST_NO>200801</CUST_NO>
      <ADDRESS>
      <SHIP_TO>200801</SHIP_TO>
      <NAME1>ISEMAR S.A.</NAME1>
      <STREET>Ruta Km 28.45</STREET>
      <CITY>Don Torcuato Paraguay</CITY>
      </ADDRESS>
      <EQUIPMENT>
      <EQUI_NO>15079</EQUI_NO>
      <EQUI_NO>15097</EQUI_NO>
      <EQUI_NO>90000-EMERGENCY</EQUI_NO>
      <EQUI_NO>90000-STOCK</EQUI_NO>
      </EQUIPMENT>
      <STORAGE_LOC>
      <STOR_LOC_NO>0001</STOR_LOC_NO>
      <DESCRIPTION>01 Parts Center</DESCRIPTION>
      <STOR_LOC_NO>0056</STOR_LOC_NO>
      <DESCRIPTION>56 HEN</DESCRIPTION>
      </STORAGE_LOC>
    </CUSTOMER_FULL_20140207_033015_001>
    Output:
    Regards,
    Akhileshkiran.

  • Validating a xml document via dtd or xml schema

    hi.
    i am trying to validate a xml document's structure via dtd or xml schema. unfortunately i dont have a clue how to do this. although i read some documents about it i didnt find a way to it yet.
    i am using dom4j to build a org.dom4j.Document from a String.
    my expectations were like this:
    - read data into string
    - create org.dom4j.Document from a string
    - after successfully creating the document calling document.validate(xmlSchema) throwing a ParseException (or something like this when the xml doesnt meet the requirements given by the schema)
    please help!

    Class org.dom4j.Document does not have a validate() method.

  • Invalid XML document - "&" character in dp-xml

    Hi guys,
    Do anyone know how to avoid XML parser exception
    in admin console throwed because one of the
    attributes in dp.xml has "&" sign in the value string (e.g. URL) ?!
    PS: I am talking about editing dp xml via amconsole.
    Thanks,
    Alex :-)

    Did this work for you? When I try & amp; it works the first time, but when I go back in to edit, it's resolved back to plain '&' and gets an error again. I certainly don't want to change it every time! Same thing happened with the entity reference.
    When I use '%26', it doesn't resolve in the browser view.
    Thanks,

  • Parse XML document with LINQ TO XML

    Hello,
    I need to parse an XML Feed that looks like this:
    <ContentAPI xmlns="http://www.geneity.co.uk/genbet/ContentAPI" status="OK" timezone="UTC" msg_stamp="NzMzNzUzNzE6MTAyMTppdA==" version="1.0" request="get_sports">
    <Sport sport_code="FOOT" name="Calcio" has_events="Y" disporder="-2"/>
    <Sport sport_code="TENN" name="Tennis" has_events="Y" disporder="1"/>
    <Sport sport_code="BASK" name="Basket" has_events="Y" disporder="2"/>
    <Sport sport_code="VOLL" name="Pallavolo" has_events="Y" disporder="4"/>
    <Sport sport_code="HAND" name="Pallamano" has_events="N" disporder="5"/>
    <Sport sport_code="ICEH" name="Hockey su Ghiaccio" has_events="Y" disporder="6"/>
    <Sport sport_code="AMFO" name="Football Americano" has_events="N" disporder="7"/>
    <Sport sport_code="BASE" name="Baseball" has_events="Y" disporder="7"/>
    </ContentAPI>
    I want to use LINQ TO XML in order to read it into an object var.
    This is the code that i wrote but i doesn't work...
     XDocument xdoc = XDocument.Load(string.Format("myURL....."));
                var Sport = from feed in xdoc.Descendants("Sport")
                            select new
                                _sport_code = feed.Attribute("sport_code").Value,
                                _name = feed.Attribute("name").Value,
                                _has_events = feed.Attribute("has_events").Value,
                                _disporder = feed.Attribute("disporder").Value
                foreach (var s in Sport)
    The program doesn't run inside the foreach loop...
    for sure the problem is on the linq to xml query...
    Thanks for your help

    Hello, I'm back again...
    Now I have to parse a second file XML with some little differences on the track:
    <ContentAPI xmlns="http://www.geneity.co.uk/genbet/ContentAPI" status="OK" timezone="UTC" msg_stamp="NzM1NTQ5MDQ6MTAyMTppdA==" version="1.0" request="get_classes_for_sport">
    <Sport sport_code="FOOT" name="Calcio" disporder="-2">
    <SBClass sb_class_id="12432" name="Italia" has_events="Y" disporder="-9999"/>
    <SBClass sb_class_id="14603" name="Euro 2016" has_events="N" disporder="-1000"/>
    </Sport>
    </ContentAPI>
    The C# code to get the SBClass elements is this:
    XDocument xdoc = XDocument.Load(string.Format(url_Get_Region_By_Lang_Sport, pCodLang, pCodSport));
    var SportRegion = from _SportRegion in xdoc.Descendants(XName.Get("Sport", "http://www.geneity.co.uk/genbet/ContentAPI")).Descendants("SBClass")
    select new
    CodSport = _SportRegion.Attribute("sport_code").Value.Trim(),
    SbRegionId = _SportRegion.Attribute("name").Value.Trim(),
    Region = _SportRegion.Attribute("has_events").Value.Trim(),
    HasEvents = _SportRegion.Attribute("disporder").Value.Trim(),
    RegionOrder = _SportRegion.Attribute("disporder").Value.Trim()
    foreach(var sptr in SportRegion)
    The program doesn't step inside the foreach loop...
    Thanks again!

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

  • Validate and update a XML document with rules

    Hi,
    In my project work, I am thinking about using oracle rules BRMS (business rule management system) to validate certain rules on xml document.
    Since I am new to the oracle rules, I want to know the feasibility of doing this with oracle rules.
    I have a specific question...
    I have XML documents that are in different schema versions. these schema are fixed but can add them in future as well.
    I have two things to do:
    1. transform a given XML document (in a one version) to another version
    2. Validate the new XML document against the rules defined in the oracle business rules.
    1.I can do the 1st task using XSLT transformation. But there is one challenge. Assume that there are new tags are added in the target schema compared to the source schema of the XML document.
    If there are optional tags to be added, I want to know if oracle rules can be used for that. Because I want to make these things done without changing the code (java) or the application internals.
    2. I have few questions on the 2nd issue. They are:
    a) can I create rules in oracle BRMS based on target schemas. (or to all of them. If so, what needs to be done if I add a new schema in future. How to update the rules?)
    b) is it possible to group the rules created above in oracle BRMS.
    Lets say
    R1, R2 rules are created against schema1 (version 1)
    R3, R4, R5 rules are created against schema2 (version 2)
    R6, R7 rules are created against schema3(version 3)
    Can I create group R1, R2 and R6 rules in to a one group (G1) and R1, R2 and R7 rules in to another group (G2).
    What are the APIs available in oracle BRMS to retrieve above defined groups at run time? (because business user can define any rules, ad group them at run time)
    Once I have the groups, How can I validate a XML document against a group created above? What are the APIs available for this.
    c) is it possible to add/update/delete tags to a XML document based on rules in oracle BRMS? if so, how?
    appreciate your valuable feedback on this..

    Hi Hareendra,
    I think you should post your question in this other forum:
    Forum Home » SOA & Process Management » SOA Suite
    Oracle Business Rules is a component used in SOA Suite
    Regards!
    Jorge

  • 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

  • How to keep the XML document in javadocs

    Hi,
    I have a class with javadocs containing <?xml....> ... </xml> document in it. I have tried to use <pre> to keep the structure. When javadoc is run it strips all the XML tags. Is it possible to keep these lines as is and not being interpreted?
    Thanks,
    -Ashish

    Hello,
    try to use <pre> and </pre> html tag around your XML document, and in your XML document change the < and > by their html special codes
    Merc?.

  • Best class to use to cache an XML document

    Hello all,
    I have an utility class representing an XML document, used withing a web application. This document shall be cached in the session since within a request and during the sessions I read it often and to several other things like XPath and XSLT.
    But I am having problems due to this Bug:
    http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6322678
    and keep bad file descriptor errors due to these stream "specialities". There is a standard way of using cached+precompiled XSL templates and I wonder if there is a similar things for XML documents.
    So I need an internal variable in my class containing the raw XML document - so using streams is not an ideal solution in regards of the bug - i am getting "bad file descriptor" errors from time to time.
    I am playing with the idea of storing the XML document within a simple String and create the required Class from it for the according operations like XPath evaluation and XSL transformation. But I think that is quite more resource hungry than reading the XML document from the filesystem each time...
    Has anyone some hints on how to keep an XML document in memory internally?
    Thanks and regards,
    Timo

    Rehi,
    So, everything works really fine! Thanks. As promised, here some examples
    with bad indentations etc...:
    Doing XSL transformation:
    import java.io.StringWriter;
    import org.w3c.dom.Document;
    import javax.xml.transform.dom.DOMSource;
    import javax.xml.transform.Templates;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.stream.StreamResult;
    TransformerFactory tFac = TransformerFactory.newInstance();
    Templates compiledXslt = tFac.newTemplates(sheet);
    Transformer transformer = compiledXslt.newTransformer();
    StringWriter sw = new StringWriter();
    StreamResult sr = new StreamResult(sw);
    transformer.transform(new DOMSource(this.doc), sr);
    System.err.println(sw.toString());************************
    Doing XPath was a surprise and was originally my problem (I called evaluate() with an InputStream that occassioannly failed), I tried also here with new DOMSource() what also failed although not being null or so... funny: evaluate() can directly be called w/ dom.Document:
    import javax.xml.xpath.XPath;
    import javax.xml.xpath.XPathFactory;
    import org.w3c.dom.Document;
    (this.doc is a org.w3c.dom.Document)
    public String getXPathEvaluationAsString(String expr) {
         try {
              XPath xp = XPathFactory.newInstance().newXPath();
              return (String)xp.evaluate(
                   expr,
                   this.doc,
                   XPathConstants.STRING
         } catch(Exception e) {
              e.printStackTrace();
         return " ";
    }Thanks and regards,
    Timo

  • Can I append an XML Document into another?

    I have a large xml document which I open into coldfusion (mx
    7), and then a smaller group of files that are opened into thier
    own xml objects. After some customization of xml text values, I
    want to append the smaller xml documents into the larger document
    at specific positions within the document tree.
    I have the code that I thought would do this, using an
    arrayappend function, but what happens is that only the root
    element of the smaller (inserted) xml document is placed into the
    main document.
    Is this possible, or do I need to modify the code so that the
    entire tree of xml data that I am appending is created on the
    fly?

    Personally I do this with XSLT.
    <cfxml variable="doc1">
    <root>
    <member id="10">
    <name>Ian</name>
    <sex>male</sex>
    </member>
    </root>
    </cfxml>
    <cfxml variable="doc2">
    <root>
    <member id="1">
    <name>Joe</name>
    <sex>male</sex>
    </member>
    <member id="2">
    <name>John</name>
    <sex>male</sex>
    </member>
    <member id="3">
    <name>Sue</name>
    <sex>female</sex>
    </member>
    </root>
    </cfxml>
    <cffile action="write" file="#expandPath("/")#\doc2.xml"
    output="#ToString(doc2)#" nameconflict="overwrite">
    <!--- METHOD ONE using a depreciated and undocumented
    method --->
    <cfset newNode = doc1.root.member.cloneNode(true)>
    <cfset doc2.changeNodeOwner(newNode)>
    <cfset doc2.root.appendChild(newNode)>
    <cfdump var="#doc2#" label="Merged by hidden functions"
    expand="no">
    <!--- METHOD TWO using XSLT --->
    <!--- create an xsl docutment--->
    <cfoutput>
    <cfsavecontent variable="transformer">
    <xsl:stylesheet xmlns:xsl="
    http://www.w3.org/1999/XSL/Transform"
    version="1.0">
    <xsl:output method="xml"/>
    <!--load the merge file -->
    <xsl:variable name="emps"
    select="document('#expandPath("/")#\doc2.xml')"/>
    <!--- this line references and XML file to be combined
    with the main file,
    I wonder if there is a way to use an XML document in memory
    here? --->
    <!-- combine the files -->
    <xsl:template match="/">
    <root>
    <!-- select all the child nodes of the root tag in the
    main file -->
    <xsl:for-each select="root/child::*">
    <!-- copy the member tag -->
    <xsl:copy-of select="."/>
    </xsl:for-each>
    <!-- and all the child nodes of the root tag in the merge
    file -->
    <xsl:for-each select="$emps/root/child::*">
    <!-- copy the member tag -->
    <xsl:copy-of select="."/>
    </xsl:for-each>
    </root>
    </xsl:template>
    </xsl:stylesheet>
    </cfsavecontent>
    </cfoutput>
    <!--- create a combined xml document --->
    <cfset doc2 = XMLparse(XMLtransform(doc1,transformer))>
    <cfdump var="#doc2#" label="Merged by XSLT"
    expand="no">

  • Loading XML document for DOM parsing

    Can anyone suggest other API's to load a XML document into memory so they can be parsed using the DOM with Java?(e.g. The "load(url)" interface method specific to IE5)
    Thanks

    Check out the DOMSample.java code came with the XML Parser for Java v2 download.
    Oracle XML Team

  • 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

Maybe you are looking for

  • How can i change the image just above password entry on login window

    I recently discovered that the image on my login window, right above where I type my password, has changed. It used to be the photo the computer took of me when I first set up my MacBook Pro. Now for some reason, the image has changed to a baseball!

  • Dispatcher dies after afew seconds

    The dispatcher on my CI dies after afew seconds. In SAPMMC the SID becomes green then the message server closes the connection to the dispatcher forcing all WP's to die. The error on the message server: ERROR => MsSClientHandle: no server provides se

  • Acrobat 9 Pro and LiveCycle

    I have Acrobat 9 pro now and for some reason it won't show up in the preview window in LC now. Do you know why?

  • App world installed but wont run

    I accidentaly deleted blackberry app world and have since downloaded it again. I can find it in application management but cannot open it to use it or get a thumbnail on main screen. Anyone have any ideas of how to fix this? Any help is appreciated!

  • Error message in MIRO

    Hi Masters of MIRO, I have REQUIRMENT where i have to display an ERROR message. currently IF company code, Ref NO & Inv Date alreday exists it issues an error message. Check if invoice already entered under accounting doc. no. 5100000010 2011 Message