Validating XML via XSD
Dear Experts,
I have this code which validates my xml to xsd:
SchemaFactory factory = SchemaFactory.newInstance(XML_SCHEMA_LANG);
Schema schema = factory.newSchema(new StreamSource("" + this.getClass().getResource(xsd)));
System.out.println("Validating :" + loc + xml + "" );
Validator validator = schema.newValidator();
validator.validate(new StreamSource(loc + xml));However if it finds a UTF-8 Special Character it throws an error like the one below in this case the UTF-8 Special Character was :
org.xml.sax.SAXParseException: An invalid XML character (Unicode: 0x12) was found in the element content of the document.
at weblogic.apache.xerces.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1189)
at weblogic.xml.jaxp.WebLogicXMLReader.parse(WebLogicXMLReader.java:135)
at weblogic.xml.jaxp.RegistryXMLReader.parse(RegistryXMLReader.java:152)Is there a way we can tell the validator to adjust to UTF-8?
Thank you.
Cordially,
The Developer
Cross-posted here: [http://forums.sun.com/thread.jspa?threadID=5396486&messageID=10760512#10760512]
Similar Messages
-
Getting an Out of memory exception while validating XML against XSD
Hello friends,
I am getting an Out Of Memory exception while validating my XML against a given XSd which is huge.
SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
saxParserFactory.setValidating(true);
SAXParser saxParser = saxParserFactory.newSAXParser();
saxParser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema");
saxParser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource",new File("C:/todelxsd.xsd")); as u may see the darkened code. this basically Loads the XSD in Memmory , and JVM throws an out of Memory exception. is there any other way round of validating an XML against an XSD where i dont have to load my XSD if not then kindly let me know the solution for above problem .
Thanks.Yes, but increasing the heap size is a temporary solution , isnt there a way where the XML can be validated against an XSD without having to load XSD in memory
-
Hi,
I would like to validate XML against XSD using SAX parser. Can any one help, where I can get information. I could get some information of XML validation against DTD. But could not get much information for XSD validation.
Which parser is good for validation against XSD? or shall I continue with SAX Parser?
KumaravelI use the "Summer 02 XML Pack" provided here at Sun, which is based on Xerces2 by Apache (http://xml.apache.org/xerces2-j/index.html). Actually with that, validation against schemas is pretty much like validation against DTDs, as long as the schema is referenced in your XML file and you switch on schema validation in the parser like
reader.setFeature("http://xml.org/sax/features/validation", true);
reader.setFeature("http://apache.org/xml/features/validation/schema", true);Xerces2 works both with DOM and SAX (I use SAX). You should browse Apache's website a bit. There's not too much information, but I guess it's enough to get started. -
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 muchYou 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); -
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); -
When validating XML against XSD DateTime not getting recognised
In the XSD the element is defined as
<xs:element name="CreateDate" type="xs:dateTime" nillable="true" minOccurs="0"/>
<xs:element name="CreateUser" type="xs:string" nillable="true" minOccurs="0"/>
<xs:element name="ModifyDate" type="xs:dateTime" nillable="true" minOccurs="0"/>
in the XML
<CreateDate>1995-04-19 14:37:43</CreateDate>
<CreateUser>JDC</CreateUser>
<ModifyDate>2010-09-21 14:37:43</ModifyDate>
When i validate it
its throwing me error.
ORA-30992 error occured at xpath
ORA-01861 leteral does not match format string.
But when i remove the Time part then it is not throwing error.
<CreateDate>1995-04-19</CreateDate>
<CreateUser>JDC</CreateUser>
<ModifyDate>2010-09-21</ModifyDate>
Help me out.Your date/time value is formatted incorrectly.
See http://www.w3.org/TR/xmlschema-2/#dateTime
The ·lexical space· of dateTime consists of finite-length sequences of characters of the form: '-'? yyyy '-' mm '-' dd 'T' hh ':' mm ':' ss ('.' s+)? (zzzzzz)?, whereSo you are missing the T between the date and time.
I will agree that the error message is not too helpful. How are you validating it and what version of Oracle (4 digits)? -
File Adapte picking up XML if XSD valid without verifing the XSD in adapter
hi',
I am facing one issue
I have a sample XML file which I want to read through BPEL process
for this I have configured the file adapter with the schema and reading the file adapter with the receive activity
next I have created one XSD file (which file adapter referes to) and one XML file,
File adapter reads it after the XML file gets validated with the XSD which is kept in a location *'/test/xsd/emp.xsd'*,
now the issue is that the file adapter is picking up and initiating the process without verifying the XSD mentioned in the adapter
it is only checking the XML file with the XSD mentioned in the XML,
for example if I have a xml file which is refering to some other schema it also gets read by file adapter without worring about what schema is mentioned in file adapter
please advice me is this the way File adapter works in Oracle BPEL or I am doing some thing wrong
I am using SOA suite 10.1.3.3.0 which is deployed in UNIX enviornment.
thanks
Yatanthanks Ketan ,
as you suggested, after adding validateXML to true, the XML is getting validated to the XSD in the adapter,
the process is getting invoked and the receive activity is throwing error of 'Invalid XML', this is perfect as I expected
however now the issue is, the file which is invalid in terms of XSD present in the file adapter is still being archived to 'success dir' i.e. 'LogicalArchiveDirectory', ideally it should have moved to fail directory,
but if the XML file is not complete or having some error in terms of the XSD it is refering to 'target namespace' and 'target location'
then it will move to the fail directory and the receive activity is also showing the error,
see this is how I have configured my bpel.xml file for the file adapter.
<activationAgents>
<activationAgent className="oracle.tip.adapter.fw.agent.jca.JCAActivationAgent" partnerLink="Read_Tph_ProdTrans_File">
<property name=*"prod_trans_success_file" type="LogicalArchiveDirectory"*>/aaa/bb/ccc/wis/tph/bpl_inbound/adjust/success</property>
<property name=*"prod_trans_incoming_file" type="LogicalDirectory"*>/aaa/bb/ccc/wis/tph/bpl_inbound/adjust/new</property>
<property name="portType">Read_ptt</property>
<property name="rejectedMessageHandlers">file:///aaa/bb/ccc/wis/tph/bpl_inbound/adjust/fail</property>
</activationAgent>
please advice how to bring this adapter to proper behaviour.
thanks
Yatan -
XML validation against registered XSD
I have registered XSD into oracle database, while validating xml against this xsd I got stuck with non-mandatory tags.
Below is the tag-XSD structure:
Status field as String:
<xs:element name="Status" nillable="false"> <xs:annotation> <xs:documentation>Values are 'N' or 'E'</xs:documentation>
</xs:annotation>
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:maxLength value="1"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
idnumber tag field as Integer:
<xs:element name="idnumber" type="xs:int" nillable="false">
<xs:annotation>
<xs:documentation>id value </xs:documentation>
</xs:annotation>
</xs:element>
As status tag is of string type and I have mentioned it as nillable = "False", but even though when I am passing this tag as <status/>, then also its validating xml.... but as i mentioned nillable property as false then it should not validate it ..... please correct me if i m wrong..
In case of idnumber tag it is of int type. In this case <idnumber/> will not work in either case even it is nillable = true or false. Means we cannt pass null values in integer field..... right?
Please suggest me how to make tag of string datatype as not nillable.
Is there any significance of using nillable = "false" in int datatype tag. Means if we want to make it as optional then need to mention it as minoccurs = 0..... is it correct?
Requirement is simple:
Just want to make some tag as optional and some as mandatory, tag can be of integer or string type.
Thanks in advance.....
Edited by: 959352 on 15-Oct-2012 00:45As status tag is of string type and I have mentioned it as nillable = "False", but even though when I am passing this tag as <status/>, then also its validating xml.... but as i mentioned nillable property as false then it should not validate it ..... please correct me if i m wrong.. The nillable attribute doesn't work that way. It's easy to look that up in any tutorial.
nillable = "true" means you allow the element to have a NULL content (different from empty string) by specifying an explicit null attribute :
<Status xsi:nil="true" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>nillable = "false" is the default behaviour.
Please suggest me how to make tag of string datatype as not nillable.
Is there any significance of using nillable = "false" in int datatype tag. Means if we want to make it as optional then need to mention it as minoccurs = 0..... is it correct?
Requirement is simple:
Just want to make some tag as optional and some as mandatory, tag can be of integer or string type. You have to be careful about the vocabulary.
In my mind, an "optional" element means you can omit it entirely in the instance document (minOccurs="0"), whereas an empty element means the start tag and end tag are there but with no content.
There are multiple ways to allow for empty or non-empty elements.
e.g. for a non-empty string :
<xs:minLength value="1"/>or, as in your example, if the content is actually constrained to a list of values, use enumerations.
xs:int datatype doesn't allow empty values (unless you use xsi:nil).
A possible solution is to build a new type by unioning (xs:union) an xs:int and an empty string type. -
Validation of xml agaist XSD in by using schemaValidate of oraxsd
Hi,
I am trying to validate an xml agaist xsd from pro*C wher i have oraxml and oraxsd libraries.
I have used a method of oraxsd and it gives error 14. pLesa let me know why i am getting this eror and how i can validate an xml by using thses functions..
int validateXSD()
xsdctx *ctx1;
xmlctx *ctx ;
uword ecode1 ;
xmlnode *root;
if(gold_debug)
printf("Validate XSD");
fflush(stdout);
root = getDocumentElement(ctx);
if(gold_debug)
printf("Validate XSD *****1 ");
fflush(stdout);
ctx1 = schemaInitialize(ctx, &ecode1);
if (ctx1==0 ) {
fprintf(stderr,"XSD initialisation failed\n");
return 1;
if(ecode1 = schemaValidate(ctx1, root, (oratext *)xsdfile)) {
if(gold_debug)
printf("Validation failed, error %u\n", ecode1);
fflush(stdout);
return 1;
}else{
if(gold_debug)
printf("*******************Scheam Validation Success*****************");
fflush(stdout);
schemaTerminate(ctx1);
return 0;
output is
Validate XSD *****1
Validation failed, error 14
Thanks,
NisaFor performance reasons the CLOB (hopefully XMLType based) is the wrong way to go. Have a look at XMLType Object Relational or Binary XML storage model.
1) The info needed can be found in the manual under "Schema evolution" and depending on your version you can use in-place or copy-evolve
2) "other way of validating" would be what / how ? Please elaborate.
3) Yep, you could. But doing it the XMLDB Oracle way would be more efficient, for example one parse only and then pinned in memory... Why would you simulate what Oracle already has optimized for you and ready to use...? -
Problemas no recebimento de XML via E-mail caracteres especiais
Boa Tarde
Estou com problemas no cenario de Validação de Assinatura com apenas um XML :
Estou recebendo um XML via E-mail !
Quando verifico o XML pelo Validador Online disponibilizado pelo SEFAZ RS ,a Assinatura é dada como Válida
e quando é pelo PI usando o serviço de Validação da Assinatura(Verify) a mesma é dada como inválida... Através do Payload na SXI_MONITOR verifiquei que além dos cacacteres ENTER entre as TAGs aparecem ESPAÇOS ...(ex.: Tag1 valor fecha Tag1 espaço Tag2 valor fecha Tag2).teria como tratar isso sem invalidar a Assinatura automáticamente ?Boa Tarde
Não sei se você chegou a receber alguns casos que lhe enviei ...! Quando ele chega ao e-mail ele já esta assim....!
Esse é nosso grande problema as vezes o parceiro não se sente obrigado em ajustar o seu sistema, uma vez que lhe é apresentado uma ferrameta do governo que valida esse mesmo arquivo rejeitado pelo serviço de Validação de *** Digital(AS JAVA)SAP ...,oque penso em fazer quanto a essa questão,.. desenvolver uma solução para tratar a excessão ..com calculo de Hash ...comparação Binária.. e outras mais...!
Só que eu não queria tomar um caminho muito distante doque a SAP possa vir a tomar com essa solução no futuro até mesmo para não depreciar essa ferramenta que é tão boa...!
Att
Ronaldo de Moraes
Edited by: Ronaldo de Moraes on Oct 21, 2009 4:58 PM -
Generate Valid XML from pl/sql
Hi,
A new-bee here. I want to know how to generate a valid xml document. I have a schema which by the way includes two other schemas. This is the code I am using but I don't know how to make sure that I insert the child nodes in the right sequence. Any sample code that you guys can provide would be greatly appreciated.
FUNCTION GenerateOrderXML(
o_ErrorCode OUT NUMBER,
o_ErrorText OUT VARCHAR2,
i_AccountID IN document.documentid%TYPE,
i_OrderName IN VARCHAR2) RETURN XMLType
IS
v_Doc XMLDOM.DOMDocument;
v_MainNode XMLDOM.DOMNode;
v_RootElmt XMLDOM.DOMElement;
v_RootNode XMLDOM.DOMNode;
v_TmpCLOB CLOB := ' ';
CURSOR CURSOR_SERVOBJ
IS
SELECT XMLTAG, XMLVALUE FROM SERVICEOBJECT
WHERE SERVICEOBJECT.ID < 500
ORDER BY SEQUENCE;
-- Create xml root element
v_Doc := XMLDOM.newDOMDocument;
v_MainNode := XMLDOM.makeNode(v_Doc);
v_RootElmt := XMLDOM.createElement(v_Doc, 'OrderRequest');
v_RootNode := XMLDOM.appendChild(v_MainNode, XMLDOM.makeNode(v_RootElmt));
-- Add OrderName, OrderType
AddChild(v_Doc, v_RootNode, 'orderName', i_OrderName);
AddChild(v_Doc, v_RootNode, 'orderType', 'NA');
-- Add all attributes
FOR v_NameValue IN CURSOR_SERVOBJ
LOOP
AddChild(v_Doc, v_RootNode, v_NameValue.XMLTAG, v_NameValue.XMLVALUE);
END LOOP;
-- XMLDOM.writeToBuffer(v_Doc, v_Buffer);
XMLDOM.writeToClob(v_Doc, v_TmpCLOB);
o_ErrorCode := 0;
RETURN XMLType.createXML(v_TmpClob);
END;The r was a typo. The messge is correct.
Here is another problem I am having. I can't import a schema that includes another schema. When I try to register the third schema I get the following error. The first two register without any errors and when I run this
select schema_url from user_xml_schemas;
I see
http://www.bbc.com/XMLSchema/sfi.xsd
http://www.bbc.com/XMLSchema/ProductModel.xsd
So why is my third schema not importing? Can you point me to any good documentation/tutorials on XML DB.
Note: Thank you for your help so far.
ERROR at line 1:
ORA-31000: Resource 'ProductModel.xsd' is not an XDB schema document
ORA-06512: at "XDB.DBMS_XMLSCHEMA_INT", line 0
ORA-06512: at "XDB.DBMS_XMLSCHEMA", line 26
ORA-06512: at "XDB.DBMS_XMLSCHEMA", line 131
ORA-06512: at line 6
1st Schema Heading
<xsd:schema xmlns="http://www.bbc.com/XMLSchema/bfi.xsd" xmlns:xsd="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.bbc.com/XMLSchema/bfi.xsd" elementFormDefault="qualified">
2nd Schema Heading
<xsd:schema xmlns="http://www.bbc.com/XMLSchema/ProductModel.xsd" xmlns:xsd="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.bbc.com/XMLSchema/ProductModel.xsd" elementFormDefault="qualified">
3rd Schema Heading
<xsd:schema xmlns="http://www.bbc.com/XMLSchema/ResourceOrder.xsd" xmlns:qb="http://www.bbc.com/XMLSchema/ProductModel.xsd" xmlns:xsd="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.bbc.com/XMLSchema/ResourceOrder.xsd" elementFormDefault="qualified">
<xsd:import namespace="http://www.bbc.com/XMLSchema/ProductModel.xsd" schemaLocation="ProductModel.xsd"/> -
Facing problem in xml schema xsd file registration
Hi,
i am facing problem in xml schema xsd file registration when
the number of column is more. It is showing persing error.
if i am deleting few column from xsd file . It is working otherwise
showing error. Is there any solution for that please suggest me.
The Error is
ORA-31011:XML parsing failed
ORA_19202: Error occurred in XML processing
LPX-00230 : (message vary time to time-like invalid tag ending etc.)
Regards
Manoranjan
and thanks in advanceWhere is you XML coming from. Are you sure it's valid. If you are hard coding it as a SQL String constant are you hitting the 4k / 32K limit on the size of SQL / PL/SQL constant. Have you tried loading the content from a bfile..
-
i've searched on how to parse xml against xsd,dtd,etc.. without the needs of internet connection..
but unfortunately, only the xsd file can be set locally and still there needs the internet connection for the other features, properties.
XML: GML file input from gui
XSD: input from gui
javax.xml
package demo;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.XMLConstants;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.xml.sax.SAXException;
public class Sample1WithJavaxXML {
public static void main(String[] args) {
URL schemaFile = null;
try {
//schemaFile = new URL("http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd");
File file0 = new File("AppSchema-C01-v1_0.xsd");
schemaFile = new URL(file0.toURI().toString());
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
//Source xmlFile = new StreamSource(new File("web.xml"));
Source xmlFile = new StreamSource(new File("C01.xml"));
SchemaFactory schemaFactory = SchemaFactory
.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
//File file1 = new File("XMLSchema.dtd");
//SchemaFactory schemaFactory = SchemaFactory
//.newInstance("javax.xml.validation.SchemaFactory:XMLSchema.dtd");
Schema schema = null;
try {
schema = schemaFactory.newSchema(schemaFile);
} catch (SAXException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
Validator validator = schema.newValidator();
try {
validator.validate(xmlFile);
System.out.println(xmlFile.getSystemId() + " is valid");
} catch (SAXException e) {
System.out.println(xmlFile.getSystemId() + " is NOT valid");
System.out.println("Reason: " + e.getLocalizedMessage());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}Xerces
package demo;
import java.io.File;
import java.util.Date;
import org.apache.xerces.parsers.DOMParser;
public class SchemaTest {
private String xmlFile = "";
private String xsdFile = "";
public SchemaTest(String xmlFile, String xsdFile) {
this.xmlFile = xmlFile;
this.xsdFile = xsdFile;
public static void main (String args[]) {
File file0 = new File("AppSchema-C01-v1_0.xsd");
String xsd = file0.toURI().toString();
SchemaTest testXml = new SchemaTest("C01.xml",xsd);
testXml.process();
public void process() {
File docFile = new File(xmlFile);
DOMParser parser = new DOMParser();
try {
parser.setFeature("http://xml.org/sax/features/validation", true);
parser.setFeature("http://apache.org/xml/features/validation/schema", true);
parser.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation",
xsdFile);
ErrorChecker errors = new ErrorChecker();
parser.setErrorHandler(errors);
System.out.println(new Date().toString() + " START");
parser.parse(docFile.toString());
} catch (Exception e) {
System.out.print("Problem parsing the file.");
System.out.println("Error: " + e);
System.out.println(new Date().toString() + " ERROR");
return;
System.out.println(new Date().toString() + " END");
}Thanks a lot Sir DrClap..
I tried to use and implement the org.w3c.dom.ls.LSResourceResolver Interface which is based on the SAX2 EntityResolver.
please give comments the way I implement it. Here's the code:
LSResourceResolver Implementation
import org.w3c.dom.ls.LSInput;
import org.w3c.dom.ls.LSResourceResolver;
import abc.xml.XsdConstant.Path.DTD;
import abc.xml.XsdConstant.Path.XSD;
public class LSResourceResolverImpl implements LSResourceResolver {
public LSResourceResolverImpl() {
* {@inheritDoc}
@Override
public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId, String baseURI) {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
LSInput input = new LSInputImpl(publicId, systemId, baseURI);
if ("http://www.w3.org/2001/xml.xsd".equals(systemId)) {
input.setByteStream(classLoader.getResourceAsStream(XSD.XML));
} else if (XsdConstant.PUBLIC_ID_XMLSCHEMA.equals(publicId)) {
input.setByteStream(classLoader.getResourceAsStream(DTD.XML_SCHEMA));
} else if (XsdConstant.PUBLIC_ID_DATATYPES.equals(publicId)) {
input.setByteStream(classLoader.getResourceAsStream(DTD.DATATYPES));
return input;
}I also implement org.w3c.dom.ls.LSInput
import java.io.InputStream;
import java.io.Reader;
import org.w3c.dom.ls.LSInput;
public class LSInputImpl implements LSInput {
private String publicId;
private String systemId;
private String baseURI;
private InputStream byteStream;
private String stringData;
public LSInputImpl(String publicId, String systemId, String baseURI) {
super();
this.publicId = publicId;
this.systemId = systemId;
this.baseURI = baseURI;
//getters & setters
}Then, here's the usage/application:
I create XMLChecker class (SchemaFactory implementation is Xerces)
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.xml.XMLConstants;
import javax.xml.stream.FactoryConfigurationError;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import abc.xml.XsdConstant.Path.XSD;
public class XMLChecker {
private ErrorMessage errorMessage = new ErrorMessage();
public boolean validate(String filePath){
final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
List<Source> schemas = new ArrayList<Source>();
schemas.add(new StreamSource(classLoader.getResourceAsStream(XSD.XML_SCHEMA)));
schemas.add(new StreamSource(classLoader.getResourceAsStream(XSD.XLINKS)));
schemas.add(new StreamSource(classLoader.getResourceAsStream("abc/xml/AppSchema.xsd")));
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
schemaFactory.setResourceResolver(new LSResourceResolverImpl());
try {
Schema schema = schemaFactory.newSchema(schemas.toArray(new Source[schemas.size()]));
Validator validator = schema.newValidator();
validator.setErrorHandler(new ErrorHandler() {
@Override
public void error(SAXParseException e) throws SAXException {
errorMessage.setErrorMessage(e.getMessage());
errorMessage.setLineNumber(e.getLineNumber());
errorMessage.setColumnNumber(e.getLineNumber());
throw e;
@Override
public void fatalError(SAXParseException e) throws SAXException {
errorMessage.setErrorMessage(e.getMessage());
errorMessage.setLineNumber(e.getLineNumber());
errorMessage.setColumnNumber(e.getLineNumber());
throw e;
@Override
public void warning(SAXParseException e) throws SAXException {
errorMessage.setErrorMessage(e.getMessage());
errorMessage.setLineNumber(e.getLineNumber());
errorMessage.setColumnNumber(e.getLineNumber());
throw e;
StreamSource source = new StreamSource(new File(filePath));
validator.validate(source);
} catch (SAXParseException e) {
return false;
} catch (SAXException e) {
errorMessage.setErrorMessage(e.getMessage());
return false;
} catch (FactoryConfigurationError e) {
errorMessage.setErrorMessage(e.getMessage());
return false;
} catch (IOException e) {
errorMessage.setErrorMessage(e.getMessage());
return false;
return true;
public ErrorMessage getErrorMessage() {
return errorMessage;
}Edited by: erossy on Aug 31, 2010 1:56 AM -
Error in validating XML against schema
Hi am getting some critical errors while Validating XML against schema
error is:
cvc-elt.1: Cannot find the declaration of element 'position' , here <position> is my root element.
my code is as follows:
package com.glemser.xmLabeling.library.component.spl;
import com.documentum.com.DfClientX;
import com.documentum.com.IDfClientX;
import com.documentum.fc.client.IDfClient;
import com.documentum.fc.client.IDfSession;
import com.documentum.fc.client.IDfSessionManager;
import com.glemser.common.helper.OperationHelper;
import org.xml.sax.*;
import org.xml.sax.helpers.DefaultHandler;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;
import java.io.CharArrayWriter;
import java.io.IOException;
import java.io.InputStream;
public class Test {
static IDfSession m_session;
public static void main(String[] args) {
try {
new Test().validate();
} catch (Exception e) {
e.printStackTrace();
private XMLReader xmlReader;
private DefaultHandler handler; // Defines the handler for this parser
private boolean valid = true;
public void validate() {
try {
SetXML setXML = new SetXML();
OperationHelper operation = new OperationHelper();
String splObjPath = "C://Documents and Settings/dparikh/My Documents/xmLabelingStage/Test.xml";//operation.executeExportOperation(m_session, new DfId(m_objectId), true);
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(false);
spf.setValidating(true);
spf.setFeature("http://xml.org/sax/features/validation", true);
spf.setFeature("http://apache.org/xml/features/validation/schema", true);
spf.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true);
if (spf.isValidating()) {
System.out.println("The parser is validating");
javax.xml.parsers.SAXParser sp = spf.newSAXParser();
sp.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema");
sp.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation", "file://C:/Documents and Settings/dparikh/My Documents/xmLabelingStage/Test.xsd");
System.out.println("The parser is validating1");
//Create XMLReader
xmlReader = sp.getXMLReader();
xmlReader.setFeature("http://apache.org/xml/features/validation/schema", true);
xmlReader.setEntityResolver(new SchemaLoader());
ContentHandler cHandler = new MyDefaultHandler();
ErrorHandler eHandler = new MyDefaultHandler();
xmlReader.setContentHandler(cHandler);
xmlReader.setErrorHandler(eHandler);
System.out.println("The parser is validating2");
parseDocument(splObjPath);
} catch (SAXException se) {
se.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
public void parseDocument(String xmlFile) {
try {
xmlReader.parse(xmlFile);
if (valid) {
System.out.println("Document is valid!");
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
class MyDefaultHandler extends DefaultHandler {
private CharArrayWriter buff = new CharArrayWriter();
private String errMessage = "";
/* With a handler class, just override the methods you need to use
// Start Error Handler code here
public void warning(SAXParseException e) {
System.out.println("Warning Line " + e.getLineNumber() + ": " + e.getMessage() + "\n");
public void error(SAXParseException e) {
errMessage = new String("Error Line " + e.getLineNumber() + ": " + e.getMessage() + "\n");
System.out.println(errMessage);
valid = false;
public void fatalError(SAXParseException e) {
errMessage = new String("Error Line " + e.getLineNumber() + ": " + e.getMessage() + "\n");
System.out.println(errMessage);
valid = false;
public class SchemaLoader implements EntityResolver {
public static final String FILE_SCHEME = "file://";
public InputSource resolveEntity(String publicId, String systemId) throws SAXException {
if (systemId.startsWith(FILE_SCHEME)) {
String filename = systemId.substring(FILE_SCHEME.length());
InputStream stream = SchemaLoader.class.getClassLoader().getResourceAsStream(filename);
return new InputSource(stream);
} else {
return null;
My XML and XSD are as below:
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="position" minOccurs="0" maxOccurs="unbounded">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="position_number" type="xsd:string"/>
<xsd:element name="position_title" type="xsd:string"/>
<xsd:element name="report_to_position" type="xsd:string"/>
<xsd:element name="incumbent" type="xsd:string"/>
<xsd:element name="operation" type="xsd:string"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<position xsi:schemaLocation="Test.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<position_number>12345</position_number>
<position_title>Sr. Engr</position_title>
<report_to_position>23456</report_to_position>
<incumbent>23456</incumbent>
<operation>INSERT</operation>
</position
Please help me out--> Could not find cached enumeration value Custom.CI.Enum.PeripheralDevice.Printer for property Type, class BMC.Custom.CI.PeripheralDevice in enumeration cache.
You must specify either the Name or Guid of an enumeration of type Custom.CI.Enum.PeripheralDevice.Type.
Be sure that you are specifying the Name property of the enumeration value you want to set, and not the DisplayName; the Internal Name is something like "IncidentCategoryEnum.Category" for out of the box enumerations, or ENUM.210ADA2282FDABC3210ADA2282FDABC
for enumerations created in the console.
you can check this by finding the enumeration in the XML or by using the the
SMLets commandlet
Get-SCSMEnumeration | ?{$_.DisplayName –eq “Printer”}
and then checking your value with
Get-SCSMEnumeration -Name "ENUM.210ADA2282FDABC3210ADA2282FDABC"
and see if you get the right displayname back -
RE: Validating XML message...
Actually I stand corrected. XML Spy does seem to provide an OLE API to XML
validation ( the isValid method on the IDocument class ) although I haven't
tested it yet.
In my previous post I was thinking of another XML product I tested earlier
in the week which did not.
-----Original Message-----
From: Shaughnessy, Kevin
Sent: Friday, April 20, 2001 08:59
To: 'Rumen Georgiev'
Cc: [email protected]
Subject: RE: Validating XML message...
Rumen,
One idea that is possible is to use an OLE interface to a 3rd party XML
product. This assumes your logic which needs to validate is running on a
Windows box. But if so, it may work. Many products have type libraries which
can be run through OLEGen to create Forte classes. Then you can use TOOL to
talk OLE to that product.
For example, XML Spy 3.5 has a type library from which I created a Forte
project. Unfortunately this product didn't offer any extra features than
Forte's XMLParser ( i.e. the API didn't allow me to validate the XML ) so I
am back to using Forte's parser until I can test another product. If you
find one that does what you want let me know.
I've used OLE a lot with Forte to get functionality from other products (
VISIO, MS Office ) that Forte doesn't provide and it works well. Its a
platform dependent solution but one that may work for you.
Kevin
-----Original Message-----
From: Rumen Georgiev [mailto:[email protected]]
Sent: Friday, April 20, 2001 07:21
To: [email protected]
Cc: [email protected]
Subject: RE: Validating XML message...
Hi Kevin,
From the answers I've got it seems Forte parser is anon-validating one. So we have to look for an external
tool to validate these messages. What I am concerned
about is the integration with Forte.
Thanks for your help!
Rumen
Rumen,
From Tech Note 11811:
"ParserFactory.makeParser() will return a default,
non-validating XML parser."
My experience is that Forte's default XML parser will
not validate but will throw an exception if the XML
document is not well formed. I'm using the DOM
model and this exception happens on the
Document.importDocument( ) method.
If you want anything more than that you'll have to do
it externally.
Kevin-----Original Message-----
From: Rumen Georgiev [mailto:[email protected]]
Sent: Thursday, April 19, 2001 11:49 AM
To: [email protected]
Subject: Validating XML message...
We have to validate inbound XML messages before
processing them. The guys on the other side are
following XMLSchema recommendations to create their
messages using xsd file for validation. We plan to
use XMLParser Forte library and as far as I know it
validates against dtd file (haven't tried yet). If
this is true we have two options:
1. Find a program to convert xsd into dtd file and
use Forte XMLParser for validation.
2. Validate the message beforehand with an external
tool. That means integration between Forte and this
tool.
I would appreciate any help with either approach. Do
you know of a program doing xsd into dtd? Have you
used any existing tool on the market to validate
using XMLSchema? Or may be there is another solution
to
this?
Thank you in advance,
Rumen
=====
Rumen Georgiev
Forte Developer
EXE Technologies
(610) 872-4400 Ext.222
Do You Yahoo!?
Yahoo! Auctions - buy the things you want at great prices
http://auctions.yahoo.com/Hi,
there is some change in the XMLSPy4.3/XMLType Library 1.2 :
Validation
One common task on documents is to validate them against an assigned schema or DTD. If the XML file has no schema or DTD already assigned, use "Document.AssignSchema" or "Document.AssignDTD" to add the necessary references to the document.
Examples:
objSpy.ActiveDocument.AssignSchema "C:\mySchema.xsd", False
or
objSpy.ActiveDocument.AssignDTD "C:\myDTD.dtd", False
If you want the user to select a schema or DTD, pass True as the second parameter to these functions to display a file-dialog. These methods only put the reference into the document and do not check the existence of the specified file. If the file path is not valid, the validation will fail.
After you have assigned a valid schema or DTD reference to your file, you are able to validate it with "Document.IsValid". IsValid needs some out-parameters that must be declared as VARIANTs to be accessible from script languages like VBScript and JavaScript.
Maybe you are looking for
-
I just updated my iPod Touch 4 Gen to iOS 5 a few weeks ago, ever since I have been having problems. At first my iPod had no album arts and if I edit the info of a song on iTunes, it wouldn't edit the info on the song on my iPod. It eventually sync m
-
About HTML and CSS styles in the Contribute Style menu
This question was posted in response to the following article: http://help.adobe.com/en_US/contribute/using/WS5b3ccc516d4fbf351e63e3d1180fba3730-7e6cCS5. html
-
How to set up web variable screen for filtering by attributes
Hi out there, My problem deals with the query variable selection screen in the web. I would like to filter some variables by their attributes in the same way it is done in the navigation item, but in the selection screen I have only the characteristi
-
Formula Pricing for RFx in e sourcing 7
Hi I am trying to use Formula Pricing in RFx in e sourcing 7.0 for line items. In Line Item Setup there are two tabs Pricing Model and Line Item Formula wherein we can add formulas. Does anyone know what is the difference b/w the two.Plz give me some
-
STO between Excisable and Non Excisable Plant
Dear All, If the material is transfer from Excisable plant to Non excisable plant, then what should be the accounting entries. In my case the material is transfer from excisable plant with duty payment and the corrosponding excise has to be accrued o