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
Similar Messages
-
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 PMHave 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 java_xml_pack-summer-02?
In jaxp1.1, we validate the xml file in this way:
c:\java -jar Validator.jar myBookStore.xml
However, in java_xml_pack-summer-02, which is latest version of jaxp, the Validator.jar is not available. So, how to validate xml file?
Pls help.develop your own validator... here is a quick and dirty one, which spits exceptions when error are met:
import java.io.*;
import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.helpers.DefaultHandler;
public class Validator
public static void main(String[] args) throws Exception {
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setValidating(true);
spf.setNamespaceAware(true);
SAXParser sp = spf.newSAXParser();
sp.parse(new File(args[0]), new DefaultHandler());
} -
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,
apkHave you looked at the XML DB FAQ thread (second post) in this forum? It has some examples for validating XML against schemas.
-
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 -
Help: How to Validate XML using SAXParser and return the entire error list
Hi,
I have a problem, I'm trying to validate a xml document against the DTD. Here Im using SAXParser and having the ErrorHandler object passed when setting the error Handler, like parser.setErrorHandler(errorHandlerObj).
I need an output like where the entire XML document is read and all the errors have to be reported with the line number.
like example:
<b>Line 6: <promp>
[Error]:Element type "promp" must be declared.
Line 8: </prompt>
[Fatal Error]:The end-tag for element type "promp" must end with a '>' delimiter.
who can i achieve this.</b>
what happens with the present code is that it throws the first error it encountered and comes out.
how can i solve this problemYou can try to set the following feature to 'true' for your SAXParser:
http://apache.org/xml/features/continue-after-fatal-error
At least Xerces supports this feature. -
How to validate xml file with XSD schema ?? in JDK1.4.2
How to validate xml file with XSD schema ?? in JDK1.4.2
i dont want to use new Xerec Jar ...
Suggest option ...Please do not double-post. http://forum.java.sun.com/thread.jspa?threadID=5134447&tstart=0
Then use Stax (Woodstock) or Saxon.
- Saish -
i've searched on how to parse xml against xsd,dtd,etc.. without the needs of internet connection..
but unfortunately, only the xsd file can be set locally and still there needs the internet connection for the other features, properties.
XML: GML file input from gui
XSD: input from gui
javax.xml
package demo;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.XMLConstants;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.xml.sax.SAXException;
public class Sample1WithJavaxXML {
public static void main(String[] args) {
URL schemaFile = null;
try {
//schemaFile = new URL("http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd");
File file0 = new File("AppSchema-C01-v1_0.xsd");
schemaFile = new URL(file0.toURI().toString());
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
//Source xmlFile = new StreamSource(new File("web.xml"));
Source xmlFile = new StreamSource(new File("C01.xml"));
SchemaFactory schemaFactory = SchemaFactory
.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
//File file1 = new File("XMLSchema.dtd");
//SchemaFactory schemaFactory = SchemaFactory
//.newInstance("javax.xml.validation.SchemaFactory:XMLSchema.dtd");
Schema schema = null;
try {
schema = schemaFactory.newSchema(schemaFile);
} catch (SAXException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
Validator validator = schema.newValidator();
try {
validator.validate(xmlFile);
System.out.println(xmlFile.getSystemId() + " is valid");
} catch (SAXException e) {
System.out.println(xmlFile.getSystemId() + " is NOT valid");
System.out.println("Reason: " + e.getLocalizedMessage());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}Xerces
package demo;
import java.io.File;
import java.util.Date;
import org.apache.xerces.parsers.DOMParser;
public class SchemaTest {
private String xmlFile = "";
private String xsdFile = "";
public SchemaTest(String xmlFile, String xsdFile) {
this.xmlFile = xmlFile;
this.xsdFile = xsdFile;
public static void main (String args[]) {
File file0 = new File("AppSchema-C01-v1_0.xsd");
String xsd = file0.toURI().toString();
SchemaTest testXml = new SchemaTest("C01.xml",xsd);
testXml.process();
public void process() {
File docFile = new File(xmlFile);
DOMParser parser = new DOMParser();
try {
parser.setFeature("http://xml.org/sax/features/validation", true);
parser.setFeature("http://apache.org/xml/features/validation/schema", true);
parser.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation",
xsdFile);
ErrorChecker errors = new ErrorChecker();
parser.setErrorHandler(errors);
System.out.println(new Date().toString() + " START");
parser.parse(docFile.toString());
} catch (Exception e) {
System.out.print("Problem parsing the file.");
System.out.println("Error: " + e);
System.out.println(new Date().toString() + " ERROR");
return;
System.out.println(new Date().toString() + " END");
}Thanks a lot Sir DrClap..
I tried to use and implement the org.w3c.dom.ls.LSResourceResolver Interface which is based on the SAX2 EntityResolver.
please give comments the way I implement it. Here's the code:
LSResourceResolver Implementation
import org.w3c.dom.ls.LSInput;
import org.w3c.dom.ls.LSResourceResolver;
import abc.xml.XsdConstant.Path.DTD;
import abc.xml.XsdConstant.Path.XSD;
public class LSResourceResolverImpl implements LSResourceResolver {
public LSResourceResolverImpl() {
* {@inheritDoc}
@Override
public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId, String baseURI) {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
LSInput input = new LSInputImpl(publicId, systemId, baseURI);
if ("http://www.w3.org/2001/xml.xsd".equals(systemId)) {
input.setByteStream(classLoader.getResourceAsStream(XSD.XML));
} else if (XsdConstant.PUBLIC_ID_XMLSCHEMA.equals(publicId)) {
input.setByteStream(classLoader.getResourceAsStream(DTD.XML_SCHEMA));
} else if (XsdConstant.PUBLIC_ID_DATATYPES.equals(publicId)) {
input.setByteStream(classLoader.getResourceAsStream(DTD.DATATYPES));
return input;
}I also implement org.w3c.dom.ls.LSInput
import java.io.InputStream;
import java.io.Reader;
import org.w3c.dom.ls.LSInput;
public class LSInputImpl implements LSInput {
private String publicId;
private String systemId;
private String baseURI;
private InputStream byteStream;
private String stringData;
public LSInputImpl(String publicId, String systemId, String baseURI) {
super();
this.publicId = publicId;
this.systemId = systemId;
this.baseURI = baseURI;
//getters & setters
}Then, here's the usage/application:
I create XMLChecker class (SchemaFactory implementation is Xerces)
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.xml.XMLConstants;
import javax.xml.stream.FactoryConfigurationError;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import abc.xml.XsdConstant.Path.XSD;
public class XMLChecker {
private ErrorMessage errorMessage = new ErrorMessage();
public boolean validate(String filePath){
final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
List<Source> schemas = new ArrayList<Source>();
schemas.add(new StreamSource(classLoader.getResourceAsStream(XSD.XML_SCHEMA)));
schemas.add(new StreamSource(classLoader.getResourceAsStream(XSD.XLINKS)));
schemas.add(new StreamSource(classLoader.getResourceAsStream("abc/xml/AppSchema.xsd")));
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
schemaFactory.setResourceResolver(new LSResourceResolverImpl());
try {
Schema schema = schemaFactory.newSchema(schemas.toArray(new Source[schemas.size()]));
Validator validator = schema.newValidator();
validator.setErrorHandler(new ErrorHandler() {
@Override
public void error(SAXParseException e) throws SAXException {
errorMessage.setErrorMessage(e.getMessage());
errorMessage.setLineNumber(e.getLineNumber());
errorMessage.setColumnNumber(e.getLineNumber());
throw e;
@Override
public void fatalError(SAXParseException e) throws SAXException {
errorMessage.setErrorMessage(e.getMessage());
errorMessage.setLineNumber(e.getLineNumber());
errorMessage.setColumnNumber(e.getLineNumber());
throw e;
@Override
public void warning(SAXParseException e) throws SAXException {
errorMessage.setErrorMessage(e.getMessage());
errorMessage.setLineNumber(e.getLineNumber());
errorMessage.setColumnNumber(e.getLineNumber());
throw e;
StreamSource source = new StreamSource(new File(filePath));
validator.validate(source);
} catch (SAXParseException e) {
return false;
} catch (SAXException e) {
errorMessage.setErrorMessage(e.getMessage());
return false;
} catch (FactoryConfigurationError e) {
errorMessage.setErrorMessage(e.getMessage());
return false;
} catch (IOException e) {
errorMessage.setErrorMessage(e.getMessage());
return false;
return true;
public ErrorMessage getErrorMessage() {
return errorMessage;
}Edited by: erossy on Aug 31, 2010 1:56 AM -
HOW TO 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. IOracle 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 -
How to validate xml againest to xsd
HI,
Xml contains multiple namespaces , I want validate xml againest to xsd. please any one can give help to me.
thanks in adwance,see the sample code which fulfill ur need...
/*--------------Validate.java------------------*/
import java.io.File;
import java.io.StringReader;
import javax.xml.XMLConstants;
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;
* This sample shows how new Validator APIs can be used to compile a standalone schema. This
* feature is useful for those applications which are developing schema and wants to check
* the validity of it as per the rules of schema language.
* Once an application has <code>Schema</code> object, it can be used to create
* <code>Validator</code> which can be used to validate an instance document against the
* schema or set of schemas this <code>Schema</code> object represents.
public class Validate
private static final boolean DEBUG = System.getProperty("debug") != null ? true : false;
/** Parser the given schema and return in-memory representation of that
* schema. Compiling the schema is very simple, just pass the path of schema
* to <code>newSchema()</code> function and it will parse schema, check the
* validity of schema document as per the schema language, compute in-memory
* representation and return it as <code>Schema</code> object. Note that If
* schema imports/includes other schemas, those schemas will be parsed too.
* @param String path to schema file
* @return Schema in-memory representation of schema.
public static Schema compileSchema(String schema) throws SAXException
//Get the SchemaFactory instance which understands W3C XML Schema language
SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
if(DEBUG)
System.out.println("schema factory instance obtained is " + sf);
return sf.newSchema(new File(schema));
}//compileSchema
* @param args the command line arguments
public static void main(String[] args)
try
//parse schema first, see compileSchema function to see how
//Schema object is obtained.
Schema schema = compileSchema("NBO.XSD");
//this "Schema" object is used to create "Validator" which
//can be used to validate instance document against the schema
//or set of schemas "Schema" object represents.
Validator validator = schema.newValidator();
//set ErrorHandle on this validator
validator.setErrorHandler(new MyErrorHandler());
//Validate this instance document against the instance document supplied
validator.validate(new StreamSource("NBWO.XML"));
} catch(Exception ex)
ex.printStackTrace();
System.out.println("GET CAUSE:");
ex.getCause().fillInStackTrace();
/*---------MyErrorHandler()-----------*/
* MyErrorHandler.java
public class MyErrorHandler implements org.xml.sax.ErrorHandler
/** Creates a new instance of MyErrorHandler */
public MyErrorHandler()
public void error(org.xml.sax.SAXParseException sAXParseException) throws org.xml.sax.SAXException
System.out.println("ERROR: " + sAXParseException.toString());
System.out.println("get error Msg : "+sAXParseException.getMessage());
public void fatalError(org.xml.sax.SAXParseException sAXParseException) throws org.xml.sax.SAXException
System.out.println("FATAL ERROR: " + sAXParseException.toString());
System.out.println("get Error Message : "+sAXParseException.getMessage());
public void warning(org.xml.sax.SAXParseException sAXParseException) throws org.xml.sax.SAXException
System.out.println("WARNING: " + sAXParseException.toString());
}With Cheers,
Prasanna T -
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; -
How to convert XML into XSD Using Altova XML Spy
Hi,
How to convert XML file into XSD Using Altova XML Spy.
I want to use that XSD as an External Def in my IR
Regards
Sumanhi
Following is the path where you could get the PDF's and zip file.
https://www.sdn.sap.com/irj/sdn/howtoguides?rid=/webcontent/uuid/5024a59a-4276-2910-7580-f52eb789194b [original link is broken]
please check out the following Heading, and at the bottom corner you will find the download option where you will get the zip file:
How to Generate XSD Schemas from Existing MDM 5.5 Repositories
You can download xomlite45.jar from sdn
copy the jar file to your java installation location like c:>java in
Java jar xomLite45.jar MyFile.xml
then you get correspondig MyFile.xsd
https://www.sdn.sap.com/irj/sdn/go/portal/prtroot/docs/library/uuid/bf0e8a97-0d01-0010-f0a2-af3b18b7f4eb -
Is there an easy way to get the xml schema/DTD for a custom entity, specifically an .XSD file for that entity (which will then be used to create a map to be able to transform the fields of the entity to a 3rd-party message format)?
So have a custom entity with lots and lots of fields. Each of the fields will map to a differently named field to match the schema of the 3rd party entity. A very common situation. Looking to use a tool like the Biztalk mapper or Altova's MapForce to generate
an .xslt file to transform the downloaded entity (service.Retrieve with all columns) to the new format. (Will implement a typical VETR pattern.)
Apparently with CRM 4 there was a call that provided this, but from 2011 has not been available. Working with a crm 2015 system.That will give a descriptor of the table and allow creation of an .XSD file, but it's really complex in terms of types, and the there's type conversion. It might be an easy way to get a schema, with the downside being it's hard to use that schema.
It seems easier to do a fetch of the record with all fields filled in using service.Retrieve, and then converting this to xml, using Microsoft's guidance leads to using https://msdn.microsoft.com/en-us/library/hh675409.aspx which will serialize the entity
into XML with all the fields converted to type string, and with complex fields likewise converted to strings with additional information about the type.
Using this it's possible using an number of tools to create an easier to use .XSD file.
However, it would seem most integrations of this type are using 3rd party CRM connectors. Perhaps this is why Microsoft hasn't provided anything direct (and took away what they did have in crm4.0 due to it generating a hard to use .XSD or due to letting
their partners continue income streams from selling connectors").
But without using 3rd party connectors, or following the still tedious method of generating .XSD (a useable .xsd), have not yet come up with an easy, automatic way to get an .XSD or to easily integrate with 3rd party message format. -
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. -
How to send XML using UTL_HTTP
I am trying to workout how to send XML data to a webserver using UTL_HTTP but am not getting any reply
I need to submit the following XML document to a server "http://api.fastsms.co.uk/api/xmlapi.php" Their instructions are "The XML Document should be posted unencoded, with a UTF-8 character set as parameter 'xml'"
If I submit the following XML on their test form
<?xml version="1.0"?>
<apirequest version="1">
<user>
<username>**USER**</username>
<password>**PASSWORD**</password>
</user>
<application>
<name>Example Application</name>
<version>1.0</version>
</application>
<inboundcheck lastid="10711399"/>
</apirequest>
I get an XML response back with the messages in my inbox.
This is the code I am trying to use to accomplish the same from PL/SQL : I know a response is coming back as there is header information - just no content. What am I doing wrong ?
l_xml VARCHAR2(5000);
req utl_http.req;
resp utl_http.resp;
header_name VARCHAR2(256); -- Response header name
header_value VARCHAR2(1024); -- Response header value
response_text VARCHAR2(4000); -- Response body
l_url VARCHAR2(100);
BEGIN
l_xml := 'xml=<?xml version="1.0"?>';
l_xml := '<apirequest version="1">';
l_xml := '<user>';
l_xml := '<username>**USER**</username>';
l_xml := '<password>**PASSWORD**</password>';
l_xml := '</user>';
l_xml := '<application>';
l_xml := '<name>Example Application</name>';
l_xml := '<version>1.0</version>';
l_xml := '</application>';
l_xml := '<inboundcheck lastid="10711399"/>';
l_xml := '</apirequest>';
-- Open HTTP connection
l_url := 'http://api.fastsms.co.uk/api/xmlapi.php';
req := utl_http.begin_request(l_url,'POST',utl_http.HTTP_VERSION_1_1);
-- Set headers for type and length
utl_http.set_header(req,'Content-Type','application/x-www-form-urlencoded');
utl_http.set_header(req,'Content-Length',to_char(length(l_xml)));
-- Write parameter
utl_http.write_text(req,l_xml);
-- Read response file
resp := utl_http.get_response(req);
-- Print out the response headers
FOR i IN 1 .. utl_http.get_header_count(resp) LOOP
utl_http.get_header(resp,i,header_name,header_value);
logging_pkg.info(header_name || ': ' || header_value);
END LOOP;
-- Print out the response body
BEGIN
LOOP
utl_http.read_text(resp,response_text);
logging_pkg.info(response_text);
END LOOP;
EXCEPTION
WHEN utl_http.end_of_body THEN
logging_pkg.info('End of body');
END;
-- close http connection
utl_http.end_response(resp);
EXCEPTION
WHEN utl_http.end_of_body THEN
utl_http.end_response(resp);
END;
Cheers,
BrentHi Billy
Yikes - how embarassing ! Thanks for pointing out my beginners mistake there. I've fixed my code - and also implemented the substitutions of parameters like you suggested - I like that approach.
Unfortunately the end result is no better - the line
utl_http.read_text(resp,response_text);
Still returns nothing back
The headers that are coming back are
Date: Thu, 04 Jul 2013 08:31:56 GMT
Server: Apache/2.2.16 (Ubuntu)
X-Powered-By: PHP/5.3.3-1ubuntu9.3
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Vary: Accept-Encoding
Content-Length: 0
Content-Type: text/html; charset=UTF-8
Connection: close
I guess I will need to try chasing it with the fastsms vendor so see if they can check my incoming request and see if there are any glaring problems. I know the xml is correct as I am now logging the xml string just before I send it and when I take that string and put it in their test form it works perfectly - something else in the puzzle is missing. I've had no experience using utl_http before - perhaps it's no possible to read the xml repsonse using this ?
Anyway, thanks for your help Billy.
ps - How do you paste your code into your message to get that formatting ?
Cheers,
Brent
Maybe you are looking for
-
I got my computer fix an he erase my itune off my computer an the only way i can restore my ipod is to erase the music I already got on there and start all over but what can i do to safe my music
-
Error in compiling SQL Expression
In the [Error in SQL Expression; thread, Kurt Reinhardt wrote "Please note, a SQL Expression can only return a single, distinct value per each record in the main recordset.", I tried this where my main Record Selection's SQL query is: {GLF_LDG_ACC_TR
-
MS word "network connection failure"
We have eight imacs(one month to 4 years old) running OS 10.4 or 10.6 connected to an admittedly old mac server on which all documents are saved, no documents are saved on local macs. Each mac has MS Word 2008 installed. Several network users are exp
-
My Coworker has Premiere Elements 7.0 on a Windows XP machine. I have Premiere Elements 9.0 on a Windows 7 machine. We are working with a SWF file that another coworker created in JING. My coworker can import the SWF into Premiere Elements 7 and pro
-
Change standard message 'No result found' of AB of overview page CRMCMP_CMG
Hi, I have a requirement, that if not result is found in views table, of assignment blocks in overviw page. Then we see a stadard message 'No result found' I want to show different messages in different assignment blocks. One way is to handle at Do_o