简体   繁体   English

使用Java中的外部DTD进行XML验证

[英]XML validation with an external DTD in Java

How can I test an xml string to see if it validates against and dtd file? 如何测试xml字符串以查看是否针对dtd文件进行验证?

I've read this question but they only see to be talking about replacing the dtd declaration on an xml file. 我已经读过这个问题,但是他们只看到正在谈论替换xml文件上的dtd声明。

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! 谢谢!

I may come back later with some code, but here's the procedure that springs to my mind: 我可能稍后会带一些代码回来,但是这是我想到的过程:

  1. Wrap string with StringReader 用StringReader包装字符串
  2. Create validating SAX parser 创建验证SAX解析器
  3. Parse file, have SAX handler track number of error instances 解析文件,使SAX处理程序跟踪错误实例的数量
  4. Valid if zero errors 如果零错误有效

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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