Libxml++:在有效性错误时返回行/列编号
Libxml++: Returning Line/Column number upon validity errors
我正在编写一个简单的C++程序来解析XML文件,以检查它的格式是否正确,以及它是否对所提供的模式有效。根据软件负责人的限制,我只能使用Libxml++。
我把所有的东西都处理好了,现在我正努力处理错误,这样它就会返回一条更有意义的错误消息。在解析错误中,这已经为我完成了,因为它返回了发生解析问题的行号和列号。然而,在Validity异常中,它只是声明捕捉到了有效性错误的元素,以及一条关于错误的短消息。
是否可以对此进行修改,使其同时返回遇到的行号和列号?问题是,如果针对一个非唯一的元素捕获了有效性错误,那么如果XML文件有数千行长,那么查找它将是非常无关的。
我使用DomParser来解析XML,并使用SchemaValidator类,如libxml++
据我所知,这在libxml++中是不可能的,但您可以直接使用底层的libxml2函数。关键是使用xmlSchemaSetValidateStructuredErrors注册结构化错误处理程序。错误处理程序接收一个xmlError,其中包含行和列编号的字段。该列存储在int2
中。请参阅以下示例程序:
#include <stdio.h>
#include <libxml/xmlschemas.h>
void errorHandler(void *userData, xmlErrorPtr error) {
printf("Error at line %d, column %dn%s",
error->line, error->int2, error->message);
}
int main() {
xmlSchemaParserCtxtPtr pctxt = xmlSchemaNewParserCtxt("so.xsd");
xmlSchemaPtr schema = xmlSchemaParse(pctxt);
xmlSchemaValidCtxtPtr vctxt = xmlSchemaNewValidCtxt(schema);
xmlSchemaSetValidStructuredErrors(vctxt, errorHandler, NULL);
xmlSchemaValidateFile(vctxt, "so.xml", 0);
return 0;
}
给定一个模式so.xsd
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="doc">
<xs:complexType>
<xs:sequence>
<xs:element name="item" minOccurs="0" maxOccurs="unbounded">
<xs:complexType>
<xs:attribute name="attr" type="xs:string"/>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
<xs:unique name="uniq">
<xs:selector xpath="item"/>
<xs:field xpath="@attr"/>
</xs:unique>
</xs:element>
</xs:schema>
和文档so.xml
<doc>
<item attr="one"/>
<item attr="two"/>
<item attr="three"/>
<item attr="one"/>
</doc>
程序打印
Error at line 5, column 23
Element 'item': Duplicate key-sequence ['one'] in unique identity-constraint 'uniq'.
相关文章:
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- 什么时候在C++中返回常量引用是个好主意
- 你能重载对象变量名本身返回的内容吗
- 为什么 Serial.println(<char[]>);返回随机字符?
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 如何获取std::result_of函数的返回类型
- QueryWorkingSet总是返回false
- (C++)分析树以计算返回错误值的简单算术表达式
- 访问者访问变体并返回不同类型时出错
- 如何返回一个类的两个对象相加的结果
- OpenInventor从9.8升级到10.4.2后,GLSL纹理返回零
- lower_bound()返回最后一个元素
- "throw expression code" 1e7 >返回 d 是什么?投掷标准::overflow_error( "too big" ) : d;意味 着?
- 奇怪的(对我来说)返回声明 - 在谷歌上找不到任何关于它的信息
- 为什么在尝试测量函数返回所需的时间时,我的运行时编号是错误的?
- 输出返回编号。等于输入字符串的单词的字符串数
- 在MATLAB中仅接受INT32PTR时,将错误编号作为字符串返回
- 为什么主函数不识别其他功能是否返回float类型编号
- Libxml++:在有效性错误时返回行/列编号
- 循环计数某个范围内的事件编号时总是返回1