Solved

Validating XML in Servlets using Schemas and Xerces parser

Posted on 2004-09-07
19
517 Views
Last Modified: 2013-11-24
Hi,

Does anyone know how I would go about, validating a piece of XML using schemas which I have.  This xml file is to be sent via a servlet (http).  I am using Xerces as my parser.

Many Thanks
Pret
0
Comment
Question by:Prett
  • 9
  • 8
  • 2
19 Comments
 
LVL 18

Expert Comment

by:armoghan
ID: 11995009
0
 

Author Comment

by:Prett
ID: 11995058
Thanks

But, I already am using similar code.  What I am after more specifically is how to point my
code at my .xsd which I have to validate any xml that I am using.
0
 
LVL 18

Expert Comment

by:armoghan
ID: 11995175
0
 
LVL 1

Accepted Solution

by:
cpa199 earned 300 total points
ID: 11995238
Use something like this (just a snippet)

String SCHEMA_LANGUAGE =
        "http://java.sun.com/xml/jaxp/properties/schemaLanguage",
XML_SCHEMA =
        "http://www.w3.org/2001/XMLSchema",
SCHEMA_SOURCE =
        "http://java.sun.com/xml/jaxp/properties/schemaSource";

Document document = null;
            
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
factory.setValidating(true);

try {

factory.setAttribute(SCHEMA_LANGUAGE,XML_SCHEMA);
factory.setAttribute(SCHEMA_SOURCE, new File("yourxsdfile.xsd"));
                         
} catch(IllegalArgumentException ex) {
                        
ex.printStackTrace();
throw new Exception("Your DOM parser is not JAXP 1.2 compliant.", ini.getProperty("CACHE") + "trapperLog.txt");
                         
}

Creating a builder from this factory (DocumentBuilder builder = factory.newDocumentBuilder()) will now include validation against the schema you specified.

Hope this helps

Carl
0
 
LVL 1

Expert Comment

by:cpa199
ID: 11995247
throw new Exception("Your DOM parser is not JAXP 1.2 compliant.", ini.getProperty("CACHE") + "trapperLog.txt");

Sorry about the above line, left in some of my specific code. Sure you know to handle this exception as you wish anyway.

Carl
0
 

Author Comment

by:Prett
ID: 11995300
Thanks Carl,

looks good, but how would I use this to validate an incoming xml streama against my schema??

Cheers
Pret.
0
 

Author Comment

by:Prett
ID: 11995309
sorry, forgot to include this in the above comment ---

Would your code work with xerces?
0
 
LVL 1

Expert Comment

by:cpa199
ID: 11995348
Yes it works with xerces. That is what I am using myself.

to parse a stream :

Call the parse method of the created Builder passing in an InputSource created with the stream or reader or whatever, check it in the API.

eg
InputSource is = new InputSource(myStreamOrReader);
Document doc = builder.parse(is);

Carl
0
 

Author Comment

by:Prett
ID: 12004785
Hi Carl,

I have tried that and am know getting :-

     [Error] :1:14: Document is invalid: no grammar found.

     [Error] :1:14: Document root element "MESSAGE", must match DOCTYPE root "null".

The xml is valid XML  and should have been validated successfully...

Any ideas??
Pret


0
What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

 
LVL 1

Expert Comment

by:cpa199
ID: 12007964
This error means that it hasn't found your schema where you pointed it to in :

factory.setAttribute(SCHEMA_SOURCE, "c:\\schema_directory\\yourschema.xsd"));

Not having seen this myself I can only assume it is looking for a relative directory it can't find, or a URI or needing a URI or something similar. Try and have a go with a few things around that area, and if you still have a problem post again with the snip of code you are using to assign the schema.

Carl
0
 

Author Comment

by:Prett
ID: 12024864
Carl,

Still having major grief with this validation malarchy.  below is the code that I am using:

String SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
    String XML_SCHEMA = "http://www.w3.org/2001/XMLSchema";
    String SCHEMA_SOURCE = "http://java.sun.com/xml/jaxp/properties/schemaSource";

    XMLHelp = new XMLHelper();

    try {

// call method to create connections to both Pre-Quest and Message Log Domino Databases
      InitConnectionBroker();

      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      factory.setNamespaceAware(true);
      factory.setValidating(true);
     
      try {
      factory.setAttribute(SCHEMA_LANGUAGE,XML_SCHEMA);
      factory.setAttribute(SCHEMA_SOURCE, new File("C:\\LA_Requests.xsd"));
      }
        catch(IllegalArgumentException x)
      {
       System.err.println("Your DOM parser is not JAXP 1.2 compliant.");
      }
0
 

Author Comment

by:Prett
ID: 12024885
It seem to find my xsd but complains with the following error(s):

(null: 13, 269): s4s-elt-schema-ns: The namespace of element 'schema' must be from the schema namespace.

(null: 14, 48): s4s-elt-schema-ns: The namespace of element 'include' must be from the schema namespace.

(null: 15, 56): s4s-elt-schema-ns: The namespace of element 'include' must be from the schema namespace.

(null: 15, 56): src-include.0: Failed to read included schema document 'RequestCommonParts.xsd'.

(null: 17, 35): s4s-elt-schema-ns: The namespace of element 'element' must be from the schema namespace.

(null: 18, 42): s4s-elt-schema-ns: The namespace of element 'complexType' must be from the schema namespace.

(null: 18, 42): s4s-att-not-allowed: Attribute 'content' cannot appear in element 'complexType'.

(null: 19, 18): s4s-elt-schema-ns: The namespace of element 'sequence' must be from the schema namespace.

(null: 36, 48): s4s-elt-schema-ns: The namespace of element 'complexType' must be from the schema namespace.

I think that it has something to with the fact that the XML that I am trying to parse uses the

"http://www.w3.org/1999/XMLSchema".  and I think that jaxp1.2 only allows the schema_language to be set to "http://www.w3.org/2001/XMLSchema";.  If this is the case do you have any idea how I can over come it?

Cheers
Pret

PS I have upped the points available..
0
 
LVL 1

Expert Comment

by:cpa199
ID: 12025108
Try just changing that schema language declaration from http://www.w3.org/1999/XMLSchema to http://www.w3.org/2001/XMLSchema in all your schemas and making sure it matches you declaration in the xml if you have an assigned schema. If still no luck try removing the assigned schema declaration from the xml as you won't need it anyway.

I hope it works this time!

Carl
0
 

Author Comment

by:Prett
ID: 12025857
Tried that still no luck......when I remove the assigned schema declarations I get namespace
errors.....can't believe that it can be so awkward just to validate a document.

getting a bit repetitive here but ....any more ideas?

Pret.
0
 
LVL 1

Expert Comment

by:cpa199
ID: 12026608
Running out of ideas here I am afraid.

Unfortunately I have never had to validate against schema that include other schema so I have no 1st hand experience with that bit.

I guess you have set the jaxp.properties file correctly so it is using xerces properly, silly question but thought I should ask incase.

Hopefully someone else can help unless I come up with any more ideas.
0
 
LVL 1

Expert Comment

by:cpa199
ID: 12026620
Oh and just thought, although this is a silly idea too but god knows, it might work. Turn off nameSpaceAware too and give it a shot, probably won't work, but no harm in trying.

Carl
0
 

Author Comment

by:Prett
ID: 12026731
Ahh now theres a thought....currently I am running all of this within jbuilder...so have not had to mess about with any jaxp.properties files or any other prop files come to think of it...
I might try to copy my code across to a proper server and see what happens.  Will let you  know how it goes... ;-)

cheers
Pret.
0
 

Author Comment

by:Prett
ID: 12043506
Carl,

Have come to the conclusion that either (or both) jaxp 1.2 and Xerces 2 don't support the
http://www.w3.org/1999/XMLSchema namespace. I have tried your code with the newer http://www.w3.org/2001/XMLSchema namespace on a different schema and it works bang on.  looks like I am going to have to create another post to see if anyone has working code for the old namespace.
Will give you the points... thanks for you help.

Cheers
Pret.
0
 
LVL 1

Expert Comment

by:cpa199
ID: 12046241
Thanks and no probs for the help. Only a shame I couldn't help more and fix it.

Carl
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now