tags:

views:

630

answers:

1

How can I test an xml string to see if it validates against and dtd file?

I've read this question but they only see to be talking about replacing the dtd declaration on an xml file.

Person.DTD

<?xml version="1.0" encoding="UTF-8"?>
<!ELEMENT person (id)>
<!ELEMENT id (#PCDATA)>

Test

@Test
public void should_serialize_a_shootout_to_xml_and_validate_against_a_dtd(){
    String xml = "<person><id>12</id></person>";        
    Assert.assertTrue(validate_xml("person.dtd",xml));
}

boolean validate_xml(String dtd_filename,String xml){
    //check xml and throw validation errors
    throw new NotImplementedException();
}

Thanks!

Edit:

sorry I'm still having problems with this

+1  A: 

I may come back later with some code, but here's the procedure that springs to my mind:

  1. Wrap string with StringReader
  2. Create validating SAX parser
  3. Parse file, have SAX handler track number of error instances
  4. Valid if zero errors