请注意,验证与格式良好是不同的。格式良好意味着语法正确的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验证是标准(出于某种原因),那么也可以使用DTD验证。
发布于 2020-05-23 05:35:33
为了使用模式(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;
}
https://stackoverflow.com/questions/60239019
复制相似问题