tags:

views:

141

answers:

6

Feels like Im about to reinvent the wheel. Im having a message payload (e.g. from a client through a socket) in XML format (in a simple java.lang.String).

Below is an example what the payload could look like:

<update>
    <type>newsource</type>
    <sources>
     <source>vedbyroad box 1492</source>
    </sources>

</update>

I want to verify that the structure of the xml document really looks like this. Feels like the correct xml tool already is available for this?

+7  A: 

Sounds like you need an XML Schema for this document. Here's a Java-based tutorial.

Brian Agnew
+2  A: 

I think what you're looking for is XML DTD (Documenttype Definition). Here's a link to get you started.

Jan Gressmann
DTD is obsolete. There's absolutely no valid reason to use it any more.
skaffman
How would you define entities without a DTD ?
Brian Agnew
Are entities not also obsolete?
skaffman
You use XML Schema Definition (XSD), as shown here: http://www.w3schools.com/Schema/default.asp
hasalottajava
+3  A: 

You need to validate your XML with a schema.

Here's an example with JAXB:

JAXBContext jc = JAXBContext.newInstance("com.acme.foo:com.acme.bar" );
Umarshaller u = jc.createUnmarshaller();  
u.setValidating(true);
SchemaFactory sf = SchemaFactory.newInstance(
      javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = sf.newSchema(new File("mySchema.xsd"));
u.setSchema(schema);
MyObject myObj = (MyObject)u.unmarshal( new File( "myFile.xml" ) );
bruno conde
+3  A: 

If you only want validation, the javax.xml.validation package can be used:

SchemaFactory schemaFactory = SchemaFactory
    .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = schemaFactory.newSchema(new File("SchemaValidation.xsd"));

Validator validator = schema.newValidator();
validator.validate(new StreamSource(new StringReader(xml)));

If you're parsing the document to some other form, you can validate as part of that process (e.g. using DocumentBuilder.setSchema).

McDowell
+1  A: 

use XSD for schema checking. DTD is obsolete.

If you want to know more about XSD in an easy way, you can download Liquid Xml Studio, it has a free community edition http://www.liquid-technologies.com/XmlStudio/XmlStudio.aspx

The best thing about this company is it provides a very user-friendly tutorial for XSD. http://www.liquid-technologies.com/Tutorials/XmlSchemas/XsdTutorial_01.aspx

janetsmith
+1  A: 

Whilst there are many people mentioning XML Schema, you may wish to look at Relax NG for something slightly simpler.

Dominic Mitchell