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>
Similar Messages
-
How to use SAX Parseto paser xml without root element
Hello,
I have big a xml file(500M) with without root element. How can I use SAXParse to parse it.A well-formed XML file has a single root element. Your parser can't deal with any other kind. So find the person who produced that file and explain politely that it's no good. (Hitting them with a big stick would be optional.)
You could write a non-XML program that reads it in and creates a new version, wrapped in a single root element, if your supplier can't fix their problem. -
End of XML file without root element
how can i know when the end of a XML file is reached if there is no root element, im using kxml.
<element id="12" nom="dan"/>
<element id="32" nom="eco"/>
<element id="34" nom="juar"/>i can parse it without no problem but when it reaches the last element it throws an exception when calling to nextTag() method, how can i knwo when stoping reading...
while(???????????)
code....
}Read the document with DOM, and append the new children, then use an empty transformer to write ti out.
-
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. -
Validate xml againt registerd schema, ignoring xsi:noNamespaceSchemaLocatio
hi,
i would like to validate received xml against registered schema, ignoring the one defined in xml. I use XMLisValid(xml_data ,schema_url) but it works only if there is no xsi:noNamespaceSchemaLocation attrubute.
This is sample xml.
<?xml version="1.0" encoding="UTF-8"?>
<!--Sample XML file generated by XMLSPY v2004 rel. 3 U (http://www.xmlspy.com)-->
<ROOT xmlns:xdb="http://xmlns.oracle.com/xdb" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://localhost/public/xsd/myapp.xsd">
<ID>0</ID>
<INFO>
<INFO_ID>0</INFO_ID>
<INFO_CONTENT>Text</INFO_CONTENT>
</INFO>
</ROOT>
Anybody knows if it is possible?
Thanks in advance..Hi,
It should work according to the documentation, but obviously it doesn't.
So I guess you'll have to consider one of these options :
- Changing the xsi:noNamespaceSchemaLocation at the source to use the URL of your registered schema instead
- The other way around : register your schema at the URL defined in the document
- Removing the xsi:noNamespaceSchemaLocation attribute prior to validation
Here's an example for the third option :
BEGIN
dbms_xmlschema.registerSchema(
schemaURL => 'myapp2.xsd'
, schemaDoc =>
'<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="ROOT">
<xs:complexType>
<xs:sequence>
<xs:element name="ID" type="xs:integer"/>
<xs:element name="INFO">
<xs:complexType>
<xs:sequence>
<xs:element name="INFO_ID" type="xs:integer"/>
<xs:element name="INFO_CONTENT" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>'
, local => true
, genTypes => false
, genTables => false
END;
SQL> declare
2
3 doc xmltype := xmltype('<?xml version="1.0" encoding="UTF-8"?>
4 <ROOT xmlns:xdb="http://xmlns.oracle.com/xdb"
5 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
6 xsi:noNamespaceSchemaLocation="http://localhost/public/xsd/myapp.xsd">
7 <ID>0</ID>
8 <INFO>
9 <INFO_ID>0</INFO_ID>
10 <INFO_CONTENT>Text</INFO_CONTENT>
11 </INFO>
12 </ROOT>');
13
14 isValid integer;
15
16 begin
17
18 doc := doc.deleteXML('/ROOT/@xsi:noNamespaceSchemaLocation','xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"');
19
20 select xmlisvalid(doc, 'myapp2.xsd') into isValid from dual;
21
22 dbms_output.put_line('isValid = '||to_char(isValid));
23
24 end;
25 /
isValid = 1
PL/SQL procedure successfully completed -
Validate xml with DOM - no grammar found
Validation with XmlSpy is OK!
Please help me. My problem is...
==========================================================
// Schema...
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified">
<xs:complexType name="ParentType">
<xs:sequence>
<xs:element name="parent1" type="xs:string"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="ChildType">
<xs:complexContent>
<xs:extension base="ParentType">
<xs:sequence>
<xs:element name="child1" type="xs:string"/>
</xs:sequence>
</xs:extension>
</xs:complexContent>
</xs:complexType>
<xs:element name="root">
<xs:complexType>
<xs:sequence>
<xs:element name="element" type="ParentType" maxOccurs="2"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
==========================================================
// Xml-file:
<?xml version="1.0" encoding="UTF-8"?>
<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://pctoiv/etktoiv/Extending.xsd">
<element xsi:type="ChildType">
<parent1/>
<child1/>
</element>
<element xsi:type="ParentType">
<parent1/>
</element>
</root>
=================================================================
//java code...
String W3C_XML_SCHEMA = "http://www.w3c.org/2001/XMLSchema";
String JAXP_SCHEMA_SOURCE = "http://java.sun.com/xml/jaxp/properties/schemaSource";
String schemaSource = "http://pctoiv/etktoiv/Extending.xsd";
javax.xml.parsers.DocumentBuilder documentBuilder = null;
org.w3c.dom.Document xmlDoc = null;
javax.xml.parsers.DocumentBuilderFactory docBuildFactory =
javax.xml.parsers.DocumentBuilderFactory.newInstance();
docBuildFactory.setNamespaceAware(true);
docBuildFactory.setValidating(true);
docBuildFactory.setAttribute(JAXP_SCHEMA_SOURCE, W3C_XML_SCHEMA);
docBuildFactory.setAttribute( JAXP_SCHEMA_SOURCE, schemaSource);
documentBuilder = docBuildFactory.newDocumentBuilder();
documentBuilder.setErrorHandler(new MyErrorHandler(System.out));
xmlDoc = documentBuilder.parse(new java.io.File("Extending.xml"));
================================================
// And errors...
org.xml.sax.SAXParseException: Document is invalid: no grammar found.
org.xml.sax.SAXParseException: Document root element "root", must match DOCTYPE root "null".Validation with XmlSpy is OK!
Please help me. My problem is...
=======================================================
==
// Schema...
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
elementFormDefault="qualified"
attributeFormDefault="unqualified">
<xs:complexType name="ParentType">
<xs:sequence>
<xs:element name="parent1" type="xs:string"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="ChildType">
<xs:complexContent>
<xs:extension base="ParentType">
<xs:sequence>
<xs:element name="child1" type="xs:string"/>
</xs:sequence>
</xs:extension>
</xs:complexContent>
</xs:complexType>
<xs:element name="root">
<xs:complexType>
<xs:sequence>
<xs:element name="element" type="ParentType"
maxOccurs="2"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
=======================================================
==
// Xml-file:
<?xml version="1.0" encoding="UTF-8"?>
<root
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://pctoiv/etktoiv/Ex
ending.xsd">
<element xsi:type="ChildType">
<parent1/>
<child1/>
</element>
<element xsi:type="ParentType">
<parent1/>
</element>
</root>
=======================================================
=========
//java code...
String W3C_XML_SCHEMA =
"http://www.w3c.org/2001/XMLSchema";
String JAXP_SCHEMA_SOURCE =
"http://java.sun.com/xml/jaxp/properties/schemaSource";
String schemaSource =
"http://pctoiv/etktoiv/Extending.xsd";
javax.xml.parsers.DocumentBuilder documentBuilder =
null;
org.w3c.dom.Document xmlDoc = null;
javax.xml.parsers.DocumentBuilderFactory
docBuildFactory =
javax.xml.parsers.DocumentBuilderFactory.newInstance();
docBuildFactory.setNamespaceAware(true);
docBuildFactory.setValidating(true);
docBuildFactory.setAttribute(JAXP_SCHEMA_SOURCE,
W3C_XML_SCHEMA);
docBuildFactory.setAttribute( JAXP_SCHEMA_SOURCE,
schemaSource);
documentBuilder =
docBuildFactory.newDocumentBuilder();
documentBuilder.setErrorHandler(new
MyErrorHandler(System.out));
xmlDoc = documentBuilder.parse(new
java.io.File("Extending.xml"));
================================================
// And errors...
org.xml.sax.SAXParseException: Document is invalid: no
grammar found.
org.xml.sax.SAXParseException: Document root element
"root", must match DOCTYPE root "null".
Try this:
private static final String JAXP_SCHEMA_SOURCE
= "http://java.sun.com/xml/jaxp/properties/schemaSource";
private static final String JAXP_SCHEMA_LANGUAGE
= "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
private static final String W3C_XML_SCHEMA
= "http://www.w3.org/2001/XMLSchema";
docBuildFactory.setNamespaceAware(true);
docBuildFactory.setValidating(true);
docBuildFactory.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA); // use LANGUAGE here instead of SOURCE
docBuildFactory.setAttribute( JAXP_SCHEMA_SOURCE, schemaSource);
documentBuilder = docBuildFactory.newDocumentBuilder();
Good luck!
Paul Niedenzu -
Validating xml with external schema
Hi,
I want to validate a xml against an external schema using java and the xml WILL NOT contain any reference to the schema. Any help in the matter is most welcome.
A typical example of such an xml is given below:
<Envelope >
<Body>
" Some content here"
</Body>
</Envelope>
I used the following code but it did not validate the xml.It simply parsed.
public class TestParser {
public static void main(String[] args) {
final String JAXP_SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
final String JAXP_SCHEMA_SOURCE = "http://java.sun.com/xml/jaxp/properties/schemaSource";
try {
SAXParserFactory saxpfactory = SAXParserFactory.newInstance();
saxpfactory.setNamespaceAware(true);//
saxpfactory.setValidating(true);//
SAXParser parser = saxpfactory.newSAXParser();
parser.setProperty(JAXP_SCHEMA_LANGUAGE, "http://www.w3.org/2001/XMLSchema");//
parser.setProperty(JAXP_SCHEMA_SOURCE, "http://www.w3.org/2001/06/soap-envelope");//
parser.parse(new File("C:\\TEMP\\request.xml"), new DefaultHandler());
} catch (FileNotFoundException fileNotFoundException) {
fileNotFoundException.printStackTrace();
} catch (IOException ioException) {
ioException.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("exiting main ");
RegardsIn the schema root element xs:schema add namespace declaration.
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
In the XML document root element add xmlns:xsi and xsi:noNamespaceSchemaLocation attributes.
<root_element xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="file://c:/testing.xsd"> -
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 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; -
HOW TO KNOW VALID XML WITH DTD ? WITHOUT PARSING ?
i am creating the xml file
i need to validate the xml with DTD to confirm is it valid or not ?
with out parsing...
could you tell me how ?
Durgawithout parsing u cant do it..
-
How to validate an xml with a schema w/o specifying the schema in the xml
I have done xml validation with xml schemas, where the xml points to the xsd to use. However, I would like to not have to specifiy the xml schema in the xml document (and can't ensure that the xml coming to us has that in it). How do I, in the java code, tell it what schema to use in validation?
Brianstatic 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)); -
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
Etbinno 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> -
hello
trying to write a unit test that validates some xml we are marshalling against a dtd. here is a snippet of code. The problem is how to specify the dtd against which the xml is to be validated. verification_transaction is our root xml element. when i run this code i get a
malformedurlexception: no protocol: verification.dtd
any ideas?
StringWriter writer = new StringWriter();
// write the doctype declaration
writer.write("<!DOCTYPE verification_transaction SYSTEM \"verification.dtd\">");
// now marshal to the writer
marshaller.marshal(spec, requestType, componentNumber, writer);
InputStream inputStream = new ByteArrayInputStream(writer.getBuffer().toString().getBytes());
Reader reader = new InputStreamReader(inputStream);
// get a sax parser that is validating
TestHandler handler = new TestHandler();
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setValidating(true);
SAXParser saxParser = factory.newSAXParser();
try {
saxParser.parse(new InputSource(reader), handler);
fail("Should have thrown exception.");
} catch (RuntimeException e) {
// pass
}Message was edited by:
shrndegruvI needed to do a bunch of things.
1.
URL url = getClass().getResource("/verification.dtd");
StringWriter writer = new StringWriter();
writer.write("<?xml version=\"1.0\"?><!DOCTYPE verification_transaction SYSTEM \"" + url + "\">");and then I had to use a handler which processed the errors (which I got from an online tutorial):
private static class MyErrorHandler extends DefaultHandler {
public void warning(SAXParseException e) throws SAXException {
System.out.println("Warning: ");
printInfo(e);
public void error(SAXParseException e) throws SAXException {
System.out.println("Error: ");
printInfo(e);
throw new SAXException("DTD Validation Error: [" + e.getMessage() + "]");
public void fatalError(SAXParseException e) throws SAXException {
System.out.println("Fatal error: ");
printInfo(e);
private void printInfo(SAXParseException e) {
System.out.println(" Public ID: " + e.getPublicId());
System.out.println(" System ID: " + e.getSystemId());
System.out.println(" Line number: " + e.getLineNumber());
System.out.println(" Column number: " + e.getColumnNumber());
System.out.println(" Message: " + e.getMessage());
} -
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) -
Validate XML with multiple XML Sechme in the same namespace
In my program, i use multiple xml schemas to validate against my xml files.
However, i found the following code do not work because all schemas in the same namespace.
Does any one have some solutions to validate multiple XML Schemas in the same namespace?
Thanks~~
static final String[] schemas = { partyInformationSchema,
itemInformationSchema,
exceptionsSchema,
salesForecastSchema,
exceptionCriteriaSchema };
factory.setAttribute(JAXP_SCHEMA_SOURCE, schemas);I have used the Object arrsy too, but it didn't work.
static final Object[] schemas = { partyInformationSchema,
itemInformationSchema,
exceptionsSchema,
salesForecastSchema,
exceptionCriteriaSchema };
Maybe you are looking for
-
Wireless connectivity lost this morning. Don't know why. When running diagnostics, I get message: The wirelss radio is not functioning. Contact HP support.
-
How can we use Custom MessageBox in SelectionChangedEvent of LongListSelector for Windows Phone 8
Dear Sir/Madam, How can we use Custom MessageBox in SelectionChangedEvent of LongListSelector for Windows Phone 8. Actually my problem is that When i am using Custom MessageBox in SelectionChangedEvent of LongListSelector,when i am click Open(Left B
-
Color LaserJet 2500N on Windows 7
I recently upgraded from WinXP Pro to Win7 Pro. The driver for the Color LaserJet 2500 installed and the printer is working. BUT....I can only print in Black and White, not in color. I hooked up the printer to a different machine still running XP
-
Trying to install CC apps, Progress bar stuck
I have spent most of my day trying to get the Creative Cloud desktop application installed (I have had to now create a new user on my computer which has seemingly fixed that), and when I tried to install Audition as a test, the progress bar got stuck
-
ADG Tree - Linked Checkbox Item Renderers
Hi Everyone, I've put together an AdvancedDataGrid that displays nodes from an XML (generated from a MySQL DB) in a tree format with two columns. The first column is the actual tree and the second column utilizes a checkbox item renderer. What I need