简体   繁体   中英

Validate XML file against several XSD and know which one validates the file (jdom2)

I would like to validate XML files against two different XSD, knowing that the XML file does not have to be validated against both of them but only one of them. Then I need to know which XSD file validates the XML file in order to access different elements.

The XSD files are of this types: sdf and csdf but I have my own versions so I do not use the schema present in the XML header (and I don't want to require the user to modify this).

Question: how to easily do the validation test and then parse the XML file (according to the right schema) using a single xml library (and if possible jdom2) ?

Currently I use javax for the validation and jdom2 to access elements but I think/hope it is possible to do the same thing using one single library, at least in order to do not parse again and again the files. And well, as pointed out in a smilar question , I'd prefer to do not take drugs in order to understand how javax works.

With JDOM 2 you can set up two different XML readers - one for each schema.

You can then read the document using SAXParser, and through the reader, and whichever one passes is the one who's schema was correct.

Consider something like ( XMLReaderXSDFactory :

sdfreader = new XMLReaderXSDFactory("http://www.es.ele.tue.nl/sdf3/xsd/sdf3-sdf.xsd");
csdfreader = new XMLReaderXSDFactory("http://www.es.ele.tue.nl/sdf3/xsd/sdf3-csdf.xsd");

Then, with those reader factories, you can set up a SAXBuilder with a different constructor :

SAXBuilder sdfbuilder = new SAXBuilder(sdfreader);
SAXBuilder csdfbuilder = new SAXBuilder(csdfreader);

Now, you can build the document through either of those. Whichever one "successfully" builds the document also has the right schema.

try {
    Document doc = sdfbuilder.build(somexml);
    System.out.println("Parsed using sdf")
    return doc
} catch (JDOMException x) {
    // parse failed, probably wrong schema....
}

try {
    Document doc = csdfbuilder.build(somexml);
    System.out.println("Parsed using csdf")
    return doc
} catch (JDOMException x) {
    // parse failed, probably wrong schema....
}

// oops, nothing works for this document...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM