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
Similar Messages
-
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 -
Hi All
please tell me how to validate xml using xsd
regardsTry 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 -
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 convert XMl file to XSD file
how to convert XMl file to XSD file ?
i have a xml file format it has to be converted to xsd file through ABAP .
Regards
Anbu Bi got the answer....
Regards
Anbu B -
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.
-
How to validate XML Digital Signature with XML DB (o PL/SQL) in Oracle 11g
Hi,
Do you know if there is possibility to validate XML Digital Signature using XML DB (or PL/SQL) in Oracle 11g?
Let say I have CLOB/XMLType containing Digitally Signed XML, and I want to validate, that thsi is proper signature. I also have public key of signer (I could store it in CLOB or file or Oracle wallet).
Is it possible to do?
If there is need to install additional component - then which one?
Regards,
PawełHi,
this is what i got from someone...
but the links he gave are not opening up...
u have to place a picture there and have to load the digital signatures as Jpegs on to the server to OA top
and have to refer them in the XML for dynamically get the signature on the reports
when u select the properties of the picture placed in the XML template,
there will be one tab with "URL"... in that u have to give the path for that jpegs
Pls refer the following documents for enabling digital signature on pdf documents.
http://iasdocs.us.oracle.com/iasdl/bi_ee/doc/bi.1013/e12187/T421739T481159.htm#5013638 (refer section 'Adding or Designating a Field for Digital Signature'
http://iasdocs.us.oracle.com/iasdl/bi_ee/doc/bi.1013/e12188/T421739T475591.htm#5013688
(Implementing a Digital Signature
Is the BI Publisher installed on your instance of version 10.1.3.4 or higher?
Pls procure a digital signature as soon as possible. The process can take time. OR we could use any certificate that you already might have OR generate a certificate using Oracle Certificate Authority for demo. -
How to validate XML files using several XSD?
hi friends i need java code for this application >?
Plz. help me urgent............Use the parser property
http://apache.org/xml/properties/schema/external-schemaLocation
to specify more than one schemas.
http://xerces.apache.org/xerces2-j/properties.html -
How to validate XML Schema in DOM?
I've got an XML file and corresponding XSD file.
How do I validate this XML file when using DOM parser?
ThanksYou can use the sun msv API.
This multi schema validator can validate documents against different sorts of Schema.
More info at http://wwws.sun.com/software/xml/developers/multischema/ -
WLI : how to validate XML / MFL instances against specifications.
Hi,
Does anybody know how a variable inside a workflow
containing XML or binary data can be validated against
an XSD or MFL?
Greetings,
Davy TochYou can tell the parser where to look for external entities. The parser allows
you to set your entity resolver -->
Using JAXP --> documentBuilder.setEntityResolver(new MyEntityResolver());
Using Xerces DOMParser --> parser.setEntityResolver(new MyEntityResolver());
Your Entity Resolver implements: InputSource resolveEntity(String publicID, String
systemID). You can implement this method to find and return an InputSource loaded
with your xsd. So the parser will call this method -- and pass in the systemID
it is looking for. Based on that systemID, you can have the method look in the
appropriate location.
"Karthik V" <[email protected]> wrote:
Jared,
That is interesting... If you do not specify the location of the schema
in
your instance document, then how do you validate it. You said your app
will
lookup the schema location. Does this mean that you do 2 step parsing?
First you parse the document and get the schema name (Say MySchema.xsd),
next you identify the schema location and parse it once more for validation
against the schema.
I know it is slightly off topic. But I would be interesed in understanding
your idea.
Thanks.
/k
"Jared" <[email protected]> wrote in message
news:[email protected]...
I think you could attack this a few ways.
If you pass the XML to your BO, you could override your parser's entityresolver
-- and redirect the xsd lookup to the actual location of XSDs. I knowthat you
said you are keeping them in the WLI repository -- but do you loadthem
into the
WLI repository from the filesystem or something? That filesystem couldbe
where
you look for the xsd.
Also, you MIGHT be able to use the XML Registry -- which also can beused
to redirect
where your BO looks for the XSD.
When I reference my XSD or DTD, I make sure that it does not containa
protocol
(eg http://). We made a rule that we will all use the filename of
the
schema
(eg asdf.xsd). Then each app could look where they wanted for theschema.
I
know this introduces problems of version control -- but we didn't wantto
have
a single point of failure for all applications just because the DTDserver
may
be down.
"Davy Toch" <[email protected]> wrote:
Hi,
I also thought of using a Business Operation, but the problem is how
to
reference the
specification in the xml instance when the specification is located
in
the
WLI repository.
I thought of recuperating the needed specification in a String variable
and
passing that too
to the Business Operation. But this poses a problem forSAXParser/DOMParser,
since
you can't specify that the specification is actually available ina
String.
Regards,
Davy Toch
"Jared" <[email protected]> wrote in message
news:[email protected]...
I don't know about MFL, but you can validate an XML against an XSDby
calling a
java class (business operation) and letting that java class validate.
I know this probably insn't the most efficient way -- or the mostappropriate
way to do it -- but it should work.
"Davy Toch" <[email protected]> wrote:
Hi,
Does anybody know how a variable inside a workflow
containing XML or binary data can be validated against
an XSD or MFL?
Greetings,
Davy Toch -
XSL to validate xml structure using XSD
Hi,
Can you please provide me a sample xsl that validates input XML against the given schema?
I have been trying with the following, but I am getting an error in jdeveloper 11g.
XML-23003: (Error) XPath 2.0 feature schema-element/schema-attribute not supported
Process exited with exit code 1.
<?xml version="1.0" encoding="windows-1252" ?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:import-schema schema-location="po1.xsd"/>
<xsl:output method="xml" version="1.0" indent="yes"/>
<!-- Root template -->
<xsl:template match="/">
<xsl:if test="not(* instance of schema-element(authorising))">
<xsl:message terminate="yes">
Source document is not a validated Provisioning list
</xsl:message>
</xsl:if>
<xsl:apply-templates/>
</xsl:template>
</xsl:stylesheet>
Thanks
923344Hi,
Can you please provide me a sample xsl that validates input XML against the given schema?
I have been trying with the following, but I am getting an error in jdeveloper 11g.
XML-23003: (Error) XPath 2.0 feature schema-element/schema-attribute not supported
Process exited with exit code 1.
<?xml version="1.0" encoding="windows-1252" ?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:import-schema schema-location="po1.xsd"/>
<xsl:output method="xml" version="1.0" indent="yes"/>
<!-- Root template -->
<xsl:template match="/">
<xsl:if test="not(* instance of schema-element(authorising))">
<xsl:message terminate="yes">
Source document is not a validated Provisioning list
</xsl:message>
</xsl:if>
<xsl:apply-templates/>
</xsl:template>
</xsl:stylesheet>
Thanks
923344 -
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 at runtime and show the exact cause of validation failure .
Hi
How can I validate my generated XML at runtine against its schema ? I have used
the validate() method and it does validate correctly against the schema but the
problem is it just returns a boolean . I need to know the exact cause of failure
(like for example The element X was supposed to contain Y,Z etc ). I need to capture
the exact exception (like a Sax Parse exception details).
How do i do that using XMLBeans ??
- BanaHi Bana,
You could use the XmlOptions.setErrorListener(Collection) method to get the detailed error message by invoking validate(option).
Kind Regards,
Jennifer -
How to get XML from its XSD?
Hi
I need to get the XML template from its XSD. Please help me understand how do I do this using a java code. Based on XSD I have to generate the XML template, which I am going to fill later.
In case there is no standard API available; then please suggest how effective will it be to parse the XDS and generate XML myself. What all consideration must be taken care of?
Regards
VijendraIndeed, the best choice is to use an XML editor that has support for this kind of operation.
In case you want to generate sample XML files with more complex conditions, oXygen (http://www.oxygenxml.com/) has such a feature : Tools->Generate Sample XML Files. ( http://www.oxygenxml.com/xml_schema_editor.html#xml_schema_instance_generator )
StylusStudio has an XML generator too:(http://www.stylusstudio.com/xml_generator.html)
But if you want to write your own generator in Java , I suggest to look at http://www.sun.com/software/xml/developers/instancegenerator/
Maybe you are looking for
-
Standard text printing missing on Smartform
Hi All, I am using standard text in Smartform. Standard text contains 'terms and conditions' hence it's used for printing in second page. For printing standard text one window other than Main window has been created in second page. Now when I am taki
-
when I run through https://testconnectivity.microsoft.com and do the Lync test for logging in we get: Couldn't sign in. Error: Error Message: A certificate chain processed, but terminated in a root certificate which is not trusted by the trust provid
-
Copy Express/ Account Segmentation
Dear All, Am trying to make a duplicate of a Database by using copy express. Note that the Chart of Account is segmented. I have managed to copy everything using copy express except the Accounts . The title Accounts are being copied but no active acc
-
How to represent more categories on graph?
Hi, i have sprint names field and each sprint name is having multiple buildnames. they have different build dates. My requirement is to show: buildnames according to sprintnames on any axis and builddates should be shown. Can anyone suggest any char
-
Finder : arrange by kinds: how to always "show all"
I hope you know what i mean. I like the new feature "arrange by kinds" but if i have a lot of files, it stills displays by one row for each kind, so i'd have to swipe left and right to look for something i want, unless I make an extra click "show all