Validate XML with XSD

Connected to:
Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - 64bit Production
with the partitioning, real application clusters, olap, data mining
and Real Application Testing options
Working with relational tables containing clob type columns (no XMLDB available) I'm not able to set up a simple validation example as below (supposed to return 1 confirming a successful validation).
declare
  xmldoc xmltype;
  sb_xml xmltype;
  valid_ number;
  xmlxsd varchar2(4000) := q'~<?xml version="1.0" ?>
                              <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
                              <xs:element name="greeting" type="xs:string" />
                              </xs:schema>~';
  xmlxml varchar2(32767) := q'~<?xml version="1.0" ?><greeting>"HELLO !"</greeting>~';
begin
  xmldoc := xmltype(xmlxml);
  sb_xml := xmldoc.createschemabasedxml();
  valid_ := sb_xml.isschemavalid(xmlxsd);
  dbms_output.put_line('IsSchemaValid (0=false,1=true): ' || to_char(valid_));
end;Thanks in advance for any kind of help provided
Etbin

no XMLDB availablenot sure if it will work without xmldb, but you might try to use java for schema validation:
SQL> CREATE OR REPLACE AND RESOLVE JAVA SOURCE NAMED "SchemaUtil"
  2  as
  3
  4  import oracle.xml.parser.schema.*;
  5  import oracle.xml.parser.v2.*;
  6  import oracle.sql.CHAR;
  7  import java.io.*;
  8
  9  public class SchemaUtil
10  {
11     public static String validation(CHAR xml, CHAR xsd)
12     throws Exception
13     {
14        //Build Schema Object
15        XSDBuilder builder = new XSDBuilder();
16        byte [] docbytes = xsd.getBytes();
17        ByteArrayInputStream in = new   ByteArrayInputStream(docbytes);
18        XMLSchema schemadoc = (XMLSchema)builder.build(in,null);
19        //Parse the input XML document with Schema Validation
20        docbytes = xml.getBytes();
21        in = new ByteArrayInputStream(docbytes);
22        DOMParser dp  = new DOMParser();
23        // Set Schema Object for Validation
24        dp.setXMLSchema(schemadoc);
25        dp.setValidationMode(XMLParser.SCHEMA_VALIDATION);
26        dp.setPreserveWhitespace (true);
27        StringWriter sw = new StringWriter();
28        dp.setErrorStream (new PrintWriter(sw));
29        try
30        {
31           dp.parse (in);
32           sw.write("The input XML parsed without errors.\n");
33        }
34        catch (XMLParseException pe)
35        {
36             sw.write("Parser Exception: " + pe.getMessage());
37          }
38        catch (Exception e)
39          {
40             sw.write("NonParserException: " + e.getMessage());
41          }
42          return sw.toString();
43     }
44   }
45  /
Java created.
SQL>
SQL> create or replace function schemavalidation(xml in varchar2,xsd in varchar2)
  2  return varchar2 is language java name 'SchemaUtil.validation(oracle.sql.CHAR,oracle.sql.CHAR)
  3                   returns java.lang.String';
  4  /
Function created.
SQL>
SQL> select schemavalidation('<?xml version="1.0" ?><greeting>"HELLO !"</greeting>',
  2                           '<?xml version="1.0" ?>
  3                          <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  4                          <xs:element name="greeting" type="xs:string" />
  5                          </xs:schema>') schemavalidation from dual
  6  /
SCHEMAVALIDATION
The input XML parsed without errors.
SQL>

Similar Messages

  • Validate XML with XSD Puntuaction Marks

    Hello all,
    I am trying to validate a XML document against a registered XML schema. The XML document contains punctuation marks (like ã, ç, õ) which cause the validation to fail. How to overcome this?
    I suspect of the encoding format the XSD and XML documents are using, encoding=UTF-8, right?
    Thank you,
    Pedro.

    Ok... just needed to change the enconding attribute of the XML document to the value of the parameter NLS_CHARACTERSET of my database.
    Unnecessary post. :-o)

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

  • How to validate xml using xsd

    Hi All
    please tell me how to validate xml using xsd
    regards

    Try using this link:
    = http://www.google.nl/search?q=XML+validate+oracle for instance or
    = use the search button on this forum and / or
    = read the FAQ on this (XML DB FAQ
    Thanks Eddie et all, for educating me via http://awads.net/wp/2006/11/14/barts-punishment-for-asking-dumb-questions (don't mind the URL , the info there is really useful)
    The following link on this site is just brilliant: http://www.albinoblacksheep.com/flash/posting.php
    Grz
    Marco
    Message was edited by:
    mgralike

  • Validate XML against XSD with imported xsd's

    Hello,
    I'm stuck for a while attempting to validate a xml against some xsd's. In the code below you can find my xsd's structure: (I need to use this structure in order to reuse the baseXsd's files.
    CommonTypes.xsd
    <?xml version="1.0" encoding="utf-8"?>
    <xs:schema id="CommonTypes" targetNamespace="http://test.com/CommonTypes"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    elementFormDefault="qualified"
    attributeFormDefault="qualified">
    <xs:simpleType name="NonEmptyString">
    <xs:restriction base="xs:string">
    <xs:minLength value="1"/>
    </xs:restriction>
    </xs:simpleType>
    </xs:schema>
    CommonLog.xsd
    <?xml version="1.0" encoding="utf-8"?>
    <xs:schema id="CommonLogConfig"
    targetNamespace="http://test.com/CommonLogConfig"
    xmlns:cmn="http://test.com/CommonTypes"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    elementFormDefault="qualified"
    attributeFormDefault="qualified">
    <xs:import schemaLocation="..\Base\CommonTypes.xsd" namespace="http://test.com/CommonTypes" />
    <xs:simpleType name="LogName">
    <xs:restriction base="xs:string"/>
    </xs:simpleType>
    <xs:simpleType name="LogPath">
    <xs:restriction base="cmn:NonEmptyString"/>
    </xs:simpleType>
    </xs:schema>
    LogConfig.xsd
    <?xml version="1.0" encoding="utf-8"?>
    <xs:schema xmlns:mlc="http://test.com/CommonLogConfig"
    targetNamespace="component1_LogConfig"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    elementFormDefault="qualified"
    attributeFormDefault="qualified">
    <xs:import schemaLocation="..\Base\CommonLogConfig.xsd" namespace="http://test.com/CommonLogConfig" />
    <xs:element name="root">
    <xs:complexType>
    <xs:sequence>
    <xs:element name="default">
    <xs:complexType>
    <xs:all>
    <xs:element name="LogName" type="mlc:LogName" fixed="component.name" />
    <xs:element name="LogPath" type="mlc:LogPath"/>
    </xs:all>
    </xs:complexType>
    </xs:element>
    </xs:sequence>
    </xs:complexType>
    </xs:element>
    </xs:schema>
    LogConfig.xml
    <?xml version="1.0" encoding="utf-8"?>
    <root xmlns="component1_LogConfig">
    <default>
    <LogName>component.name</LogName>
    <LogPath></LogPath>
    </default>
    </root>
    As you can probably notice, the <LogPath> key on the LogConfig is empty, but, it is defined as a NonEmptyString type. That is the way I'm validating the xml against xsd:
    FileStream stream = new FileStream("LogConfig.xml", FileMode.Open);
    XmlValidatingReader vr = new XmlValidatingReader(stream, XmlNodeType.Element, null);
    vr.Schemas.Add(null, "LogConfig.xsd");
    vr.ValidationType = ValidationType.Schema;
    vr.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);
    while (vr.Read()) ;
    The validationCallBack is not being fired.
    I suppose it is possible since the visual studio show me the error at compile time:

    Well, it is weird, but, the code below works when validating the NonEmptyString type:
    XmlSchemaSet schemaSet = new XmlSchemaSet();
    schemaSet.Add(null, "LogConfig.xsd");
    XDocument doc1 = XDocument.Load("LogConfig.xml");
    doc1.Validate(schemaSet, new ValidationEventHandler(ValidationCallBack), false);
    However, if I leave the <LogName> empty it does not valid the values set on xsd fixed attribute, 
    The solution?
    Well, I'm validating the same xml twice, the code above and the code on my first question.

  • Error validating xml with xsd schema on JSDK 1.4

    Hi All,
    Asked to me do it a Web Service client in Java and validate its xml answer with an xsd file using 1.4 plataform.
    I googled and I saw many samples to 1.5 plataform, and few samples to 1.4, but anyway I tried to do what they asked to me.
    I got connect with service, got the response and so I went to validate that xml with an xsd file.
    But I got an error on that task. The error occurs in the following line
    "Schema schema = factory.getSchema();"
    Bellow my code
    final String JAXP_SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
              final String W3C_XML_SCHEMA = "http://www.w3.org/2001/XMLSchema";
              final String schemaSource = "C:\\GetAuthorizationServiceOutput.xsd";
              final String JAXP_SCHEMA_SOURCE = "http://java.sun.com/xml/jaxp/properties/schemaSource";
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();          
              factory.setNamespaceAware(true);
              factory.setValidating(true);
              try {
              factory.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
              factory.setAttribute(JAXP_SCHEMA_SOURCE,new File(source));
              catch (IllegalArgumentException x) {
                   System.out.println(x.getMessage());
    DocumentBuilder builder = null;
              Document document = null;
              try {
                   builder = factory.newDocumentBuilder();
                   document = builder.parse(new InputSource(new StringReader(ret.toString())));
              } catch (ParserConfigurationException e) {
                   e.printStackTrace();
              } catch (SAXException e) {
                   e.printStackTrace();
              } catch (IOException e) {
                   e.printStackTrace();
              **Schema schema = factory.getSchema();**
              Validator validator = schema.newValidator();
              try {
                   validator.validate(new DOMSource(document));
              } catch (SAXException e) {
                   e.printStackTrace();
              } catch (IOException e) {
                   e.printStackTrace();
    and here is the exception :
    Caused by: java.lang.NoSuchMethodError: javax.xml.parsers.DocumentBuilderFactory.getSchema()Ljavax/xml/validation/Schema;
    Method onLinkClicked of interface wicket.markup.html.link.ILinkListener targeted at component [MarkupContainer [Component id = btBack, page = br.com.weev.finan.mkb_er.extranet.view.relations.RelationsDetails, path = 30:form:btBack.RelationsDetails$4, isVisible = true, isVersioned = true]] threw an exception
    wicket.WicketRuntimeException: Method onLinkClicked of interface wicket.markup.html.link.ILinkListener targeted at component [MarkupContainer [Component id = btBack, page = br.com.weev.finan.mkb_er.extranet.view.relations.RelationsDetails, path = 30:form:btBack.RelationsDetails$4, isVisible = true, isVersioned = true]] threw an exception
         at wicket.RequestListenerInterface.invoke(RequestListenerInterface.java:198)
         at wicket.request.target.component.listener.ListenerInterfaceRequestTarget.processEvents(ListenerInterfaceRequestTarget.java:74)
         at wicket.request.compound.DefaultEventProcessorStrategy.processEvents(DefaultEventProcessorStrategy.java:65)
         at wicket.request.compound.AbstractCompoundRequestCycleProcessor.processEvents(AbstractCompoundRequestCycleProcessor.java:57)
         at wicket.RequestCycle.doProcessEventsAndRespond(RequestCycle.java:896)
         at wicket.RequestCycle.processEventsAndRespond(RequestCycle.java:929)
         at wicket.RequestCycle.step(RequestCycle.java:1010)
         at wicket.RequestCycle.steps(RequestCycle.java:1084)
         at wicket.RequestCycle.request(RequestCycle.java:454)
         at wicket.protocol.http.WicketServlet.doGet(WicketServlet.java:219)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:689)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:237)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:157)
         at org.springframework.orm.hibernate3.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:198)
         at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:75)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:186)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:157)
         at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:214)
         at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:104)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:520)
         at org.apache.catalina.core.StandardContextValve.invokeInternal(StandardContextValve.java:198)
         at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:152)
         at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:104)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:520)
         at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:137)
         at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:104)
         at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:118)
         at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:102)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:520)
         at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
         at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:104)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:520)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:929)
         at org.apache.coyote.tomcat5.CoyoteAdapter.service(CoyoteAdapter.java:160)
         at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:799)
         at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:705)
         at org.apache.tomcat.util.net.TcpWorkerThread.runIt(PoolTcpEndpoint.java:577)
         at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:683)
         at java.lang.Thread.run(Thread.java:534)
    Caused by: java.lang.reflect.InvocationTargetException
         at sun.reflect.GeneratedMethodAccessor342.invoke(Unknown Source)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
         at java.lang.reflect.Method.invoke(Method.java:324)
         at wicket.RequestListenerInterface.invoke(RequestListenerInterface.java:187)
         ... 39 more
    Caused by: java.lang.NoSuchMethodError: javax.xml.parsers.DocumentBuilderFactory.getSchema()Ljavax/xml/validation/Schema;
         at br.com.weev.finan.mkb_er.business.manager.impl.RelationManagerImpl.getAuthorizationService(RelationManagerImpl.java:152)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
         at java.lang.reflect.Method.invoke(Method.java:324)
         at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:296)
         at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:177)
         at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:144)
         at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:107)
         at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:166)
         at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
         at $Proxy22.getAuthorizationService(Unknown Source)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
         at java.lang.reflect.Method.invoke(Method.java:324)
         at wicket.proxy.LazyInitProxyFactory$JdkHandler.invoke(LazyInitProxyFactory.java:377)
         at wicket.proxy.$Proxy39.getAuthorizationService(Unknown Source)
         at br.com.weev.finan.mkb_er.extranet.view.relations.RelationsDetails$4.onClick(RelationsDetails.java:125)
         at wicket.markup.html.link.Link.onLinkClicked(Link.java:254)
         ... 43 more
    It's my first time doing that, so I'm confuse to do it.
    Thank you
    Juliano.

    This is how.
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.transform.dom.DOMResult;
    import javax.xml.transform.dom.DOMSource;
    import javax.xml.validation.Schema;
    import javax.xml.validation.SchemaFactory;
    import javax.xml.validation.Validator;
    DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
    dbfac.setNamespaceAware(true);
    SchemaFactory factory1 = SchemaFactory
                        .newInstance("http://www.w3.org/2001/XMLSchema");
    Schema schema = factory1.newSchema(new File("person.xsd"));
    dbfac.setSchema(schema);
    DocumentBuilder dbparser1 = dbfac.newDocumentBuilder();
    Document doc1 = dbparser1.parse(new File("person.xml"));
    Validator validator1 = schema.newValidator();
    DOMSource dm1 = new DOMSource(doc1);
    DOMResult domresult1 = new DOMResult();
    validator1.validate(dm1, domresult1);

  • Validate XML with Schema?

    So, according to Adobe...
    quote:
    Dreamweaver CS3 continues to support not only the creation
    and editing of XML and XSL files, but it also allows you to import
    DTDs and schemas and to validate XML documents.
    Does anyone know how to accomplish this task? Adobe's
    documentation on this topic seems be less current than their
    marketing material.
    I mean, I'm assuming from the way this is worded it means
    that you can "import DTDs and schemas and ... validate XML
    documents"
    with said schemas. Or is this just some shifty marketing
    trickery which really means you can import (i.e., open) a DTD or
    schema, and, as a completely unrelated task, you can "validate"
    your XML file - to the extent that Dreamweaver will tell you if you
    forgot to close a tag?

    I tried to move all the xml, class and xsd files in the same folder and it still didn't work...
    And I can't hard coded the xsd file on the document... so the only way is to set the xsd location inside the java codes... here's what I have:
    static final String JAXP_SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
    static final String W3C_XML_SCHEMA = "http://www.w3.org/2001/XMLSchema";
    static final String JAXP_SCHEMA_SOURCE = "http://java.sun.com/xml/jaxp/properties/schemaSource";
    File xsdFile = new File("schema.xsd");
    saxParser.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
    saxParser.setProperty(JAXP_SCHEMA_SOURCE, xsdFile);
    Please help... thx.

  • HOW TO USE isSchemaValid() in oracle 9i to validate XML against XSD

    Hi
    I am trying to validate xml file against xsd in oracle 9i.The steps are as follows:
    *1.Created directory for xml and xsd file location:*
    CREATE or replace DIRECTORY XML_DATA AS 'D:\prod\sample xml and xsd;
    *2.Register the schema*
    DECLARE
    bf5 BFILE;
    BEGIN
    -- Register the schema
    dbms_lob.filecloseall;
    bf5 := BFILENAME('XML_DATA','xml1.xsd');
    DBMS_XMLSCHEMA.registerSchema('http://www.example.com/schemas/ipo.xsd',bf5,TRUE, TRUE, FALSE,TRUE,TRUE);
    -- dbms_lob.fileclose(bf5);
    END;
    *3.creatibg table to store xml files*
    CREATE TABLE po_tab2 (id NUMBER,xmlcol SYS.XMLType) ;
    *4.Inserting xml file into the table and validating that file with xml schema*
    declare
    aa clob:=' ';
    b varchar2(4000);
    c xmltype;
    begin
    dbms_lob.filecloseall;
    aa:= GETCLOBDOCUMENT('XML_DATA','example.XML','WE8MSWIN1252');
    INSERT INTO po_tab2 (ID, XMLCOL)
    VALUES
    (104,sys.XMLType.createXML(aa));
    commit;
    --c:=sys.xmltype.createXml(aa);
    c:=xmltype(aa);
    b:=VerifyXML(c,'http://www.example.com/schemas/ipo.xsd');
    dbms_output.put_line(b);
    end;
    _5.VerifyXML function is:_
    create or replace
    function VerifyXML( xml xmltype, xmlSchema varchar2 ) return varchar2 AUTHID DEFINER is
    xmlURL varchar2(4000);
    begin
    select
    s.qual_schema_url into xmlURL
    from user_xml_schemas s
    where s.schema_url = xmlSchema;
    if xml.isSchemaValid(xmlURL,'ManageRolloutRegionNotification') =1 then
    return( 'Valid. The supplied XML complies with XSD '||xmlURL );
    else
    -- return null;
    return(sqlcode|| 'Failed. The supplied XML does not comply with XSD '||xmlURL );
    end if;
    exception when others then
    return(sqlcode);
    end;
    _6.PROBLEM:_
    the problem is the function is always returning 'Failed ' status even though I am giving the correct file.. Is there any method to find the reason for failure. These codes are working fine oracle 11g. currently i am working in 9i version 9.2.0.1.0. I

    Oracle 9iR2 is not supported anymore.
    Oracle 9.2.0.8 is in sustained support.
    Oracle 9.2.0.1 is not supported at all.
    Upgrade to 11gR2.
    Sybrand Bakker
    Senior Oracle DBA

  • Validate xml with complextype schema without root element!

    Hi All!
    I have a problem that. I want to validate a xml data of complextype but the schema i want to validate is[b] not have root element.
    For example:
    The schema like that
    <?xml version="1.0" encoding="UTF-8"?>
    <xs:schema targetNamespace="www.thachpn.test" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="www.thachpn.test" elementFormDefault="qualified" attributeFormDefault="unqualified">
         <xs:complexType name="Name">
              <xs:sequence>
                   <xs:element name="FirstName" type="xs:string"/>
                   <xs:element name="LastName" type="xs:string"/>
              </xs:sequence>
         </xs:complexType>
    </xs:schema>
    and the xml data i want to validate like this
    <?xml version="1.0" encoding="UTF-8"?>
    <Name xmlns="www.thachpn.test" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
         <FirstName>Pham</FirstName>
         <LastName>Thach</LastName>
    </Name>
    My Algorithm is like that:
    I create a complextype object by above schema
    then i create new element with given name and namespace
    after that i use schema of this element to validate xml data.
    I use xmlparserv2 lib of oracle
    But i can not find how to create complextype from schema or create element with have complextype.
    Please help me.
    Thanks a lot!

    <?xml version="1.0" encoding="UTF-8"?>
    Modify the schema.
    Add a root element.
    <xs:schema targetNamespace="www.thachpn.test" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="www.thachpn.test" elementFormDefault="qualified" attributeFormDefault="unqualified">
    <xsd:element name="Name" type="Name"/>
    <xs:complexType name="Name">
    <xs:sequence>
    <xs:element name="FirstName" type="xs:string"/>
    <xs:element name="LastName" type="xs:string"/>
    </xs:sequence>
    </xs:complexType>
    </xs:schema>

  • Validate XML against XSD using PLSQL

    Hi,
    We now need some kind of automated solution that will pick
    up the XMLs from a specific location or table and validate them
    against the XSD in only Oracle PLSQL.
    The validation of the XML against the XSD should take place when the XML is parsed.
    I want to know how first the XSD's are stored or registered in the Oracle XDB repository.
    Please can anyone suggest me how this can be done with a simple example
    with a sample XML and XSD?
    Regards,
    Marlon.

    Hi, I'm not an expert but I've been reading a lot and I found this and it works. I'll hope it is useful.(Oracle 10)
    declare
    -- Local variables here
    res BOOLEAN;
    tempXML XMLType;
    xmlDoc XMLType;
    xmlSchema XMLType;
    schemaURL varchar2(256) := 'testcase.xsd';
    schemaPath varchar2(256) := '/public/testcase.xsd';
    begin
    dbms_xmlSchema.deleteSchema(schemaURL,4);
    -- Test statements here
    xmlSchema := xmlType(
    '<?xml version="1.0" encoding="UTF-8"?>
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xdb="http://xmlns.oracle.com/xdb"
    elementFormDefault="qualified" attributeFormDefault="unqualified">
    <xs:element name="root" xdb:defaultTable="ROOT_TABLE">
    <xs:complexType>
    <xs:sequence>
    <xs:element name="child1"/>
    <xs:element name="child2"/>
    </xs:sequence>
    </xs:complexType>
    </xs:element>
    </xs:schema>
    dbms_xmlschema.registerSchema(schemaURL,
    xmlSchema , --xdbURIType(schemaPath).getClob(),
    TRUE,TRUE,FALSE,TRUE
    xmlDoc:=xmltype('<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="' || schemaURL || '"><child1>foo</child1><child2>bar</child2></root>');
    dbms_output.put_line(xmlDoc.getStringVal());
    xmlDoc.schemaValidate();
    END;

  • Validate XML using XSD (XML Schema)

    Hi experts.
    Is there any way in ABAP to validate XML file against specified XSD file?
    I found only possibility to validate against DTD, but no XSD. As far as I know this is only possible in Java, or is a part of XI. Is it doable without Java or XI (on NetWeaver 2004s)?
    Help appreciated (and rewarded).
    Regards, Frantisek.

    Hello
    Perhaps you missed this link: [How to Perform XML Validations in SAP NetWeaver Process Integration 7.1|https://www.sdn.sap.com/irj/sdn/go/portal/prtroot/docs/library/uuid/d06dff94-9913-2b10-6f82-9717d9f83df1]
    Regards
      Uwe

  • Validate xml with PL/SQL Parser

    Hi,
    i have an xml DTD into a VARCHAR2 variable and an xml document
    into a CLOB, i'd like to know how to validate the xml with my
    DTD using PL/SQL API for xml.
    Sorry for my terrible english (i'm not english) :-)
    Tank you.

    Here's an example:
    set serveroutput on
    DECLARE
      p xmlparser.parser;
      d xmldom.DOMDocument;
      dtd xmldom.DOMDocumentType;
      v varchar2(32700);
      good clob;
      bad clob;
      xml_parse_error exception;
      pragma exception_init(xml_parse_error,-20100);
    BEGIN
      bad   := '<!DOCTYPE Department SYSTEM "test.dtd"><Deprtment/>';
      good  := '<!DOCTYPE Department
    SYSTEM "test.dtd"><Department/>';
      v := '<!ELEMENT Department EMPTY>';
      p := xmlparser.newParser;
      xmlparser.parseDTDBuffer(p,v,'Department');
      xmlparser.setDoctype(p,xmlparser.getDoctype(p));
      xmlparser.setValidationMode(p,TRUE);
      xmlparser.parseClob(p,good);
      xmlparser.parseClob(p,bad);
      xmlparser.freeParser (p);
    EXCEPTION
      WHEN xml_parse_error THEN
         DBMS_OUTPUT.PUT_LINE(sqlerrm);
         xmlparser.freeParser (p);
    END;

  • Problem validating XML with XSD

    Hi everyone. I have an xsd schema and I want to validate some XML doc with the schema using SAX parser.
    The user make the xml and then upload it to the server.
    I want to enable client side validation but, for security reasons, I want also to validate this document when it's uploaded to the server.
    The schema called ContentSchema.xsd
    <?xml version="1.0" encoding="ISO-8859-1" ?>
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
         targetNamespace="www.mysite.com/Content" xmlns="www.mysite.com/Content">
         <xs:element name="content">
              <xs:complexType>
    A document produced by the client starts in this way:
    <?xml version="1.0" encoding="UTF-8"?>
    <p:content xmlns:p="www.mysite.com/Content" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="www.mysite.com/Content ContentSchema.xsd">
    in this way users can validate the XML doc before uploading. If the XSD is in the same folder of the uploaded XML the validation is ok.
    The problem is that, on the server, I've stored the xsd file in a folder and I want the SAX parser to use this xsd to validate the XML. Even I pass the complete URI of the file to the parser, it won't work:
    SAXParserFactory spf = SAXParserFactory.newInstance();
              spf.setValidating(true);
              spf.setNamespaceAware(true);
              spf.setFeature("http://apache.org/xml/features/validation/schema",true);
              spf.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true);
              SAXParser sp=spf.newSAXParser();
              sp.setProperty("http://apache.org/xml/properties/schema/external-schemaLocation", schemaURL );
    I set the schemURL with setProperty method but it's like the parser is looking for the XSD in the URL declared in the XML doc and not in the URI I specify. Anyone can help me?
    Thank you very much

    You will have to associate the schema with the namespace, like in your xsi:schemaLocation attribute.
    Try something like this:
    sp.setProperty("http://apache.org/xml/properties/schema/external-schemaLocation", "www.mysite.com/Content "+schemaURL);

  • Validate XML against XSD

    Hi. I need to validate an XML file against XSD schema.
    How can I do it with PL/SQL?
    Thanks a lot
    Alejandro

    Well, it is weird, but, the code below works when validating the NonEmptyString type:
    XmlSchemaSet schemaSet = new XmlSchemaSet();
    schemaSet.Add(null, "LogConfig.xsd");
    XDocument doc1 = XDocument.Load("LogConfig.xml");
    doc1.Validate(schemaSet, new ValidationEventHandler(ValidationCallBack), false);
    However, if I leave the <LogName> empty it does not valid the values set on xsd fixed attribute, 
    The solution?
    Well, I'm validating the same xml twice, the code above and the code on my first question.

  • How to Validate XML against XSD through PL/SQL?

    Hi friends,
    I m new to this forum. This is my first query.
    In our project, we are trying to generate output XML using PL/SQL procedure. I have done that successfully. Now my problem is I have to validate this against our XSD. How will I do that? Can you provide me with a sample example.
    Thanks to all in advance.
    Regards,
    apk

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

Maybe you are looking for