注意,验证和格式良好是两码事。格式良好意味着一个语法上正确的 XML 文档。
有效性是一个更狭义的东西:它还要求文档通过一个特定于文档格式的标准。
我的研究表明,XML验证有两个标准。DTD和XSD。DTD属于一个XML文档,而XSD属于一个XML标签。很明显,它也可以设置在XML文档的根标签上,比如这样。
<?xml version="1.0" encoding="utf-8"?>
<RootTag xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="./example.xsd">
<!-- ... -->
</RootTag>
逻辑上讲,下面的C++代码,读取和验证文档,应该是可行的。
int main(int argc, char* argv[]) {
try {
xmlpp::DomParser parser;
parser.set_validate();
parser.set_substitute_entities(); //We just want the text to be resolved/unescaped automatically.
parser.parse_file("example.xml");
...
}
catch(const std::exception& ex) {
std::cout << "Exception caught: " << ex.what() << std::endl;
}
return 0;
}
然而,这并没有发生。这段代码出现了以下错误
Exception caught:
Validity error:
File example.xml, line 2, column 111 (error):
Validation failed: no DTD found !
在我看来,libxml++希望以某种方式专门通过DTD进行验证。一个模拟的XML文件,但使用DTD验证器,工作起来没有任何问题。
为什么呢?我可以用XSD来验证整个XML文档吗?这是libxml2的一个限制,是我在libxml2文档中遗漏了什么,还是仅仅是标准?
对于验证文档,我更倾向于XSD,但如果这是标准的话,DTD验证也是可以的(基于某些原因)。
为了使用模式(XSD)进行验证,你需要准备一个xmlpp::XsdValidator对象,并使用它来验证你的XML。
验证器的准备示例。
xmlpp::DomParser schema;
schema.parse_file("example.xsd");
xmlpp::XsdValidator validator;
validator.parse_document( schema.get_document() );
验证器的使用示例。
try {
xmlpp::DomParser parser;
parser.parse_file("example.xml");
validator.validate( parser.get_document() );
// Use the validated XML...
}
catch(const xmlpp::exception &e) {
std::cerr << "Went wrong: " << e.what() << std::endl;
}