c++ - Libxml++ : Returning Line/Column number upon validity errors

标签 c++ xml xsd xml-parsing libxml2

我正在编写一个简单的 C++ 程序来解析 XML 文件,以检查它的格式是否正确,以及它对于提供的架构是否有效。根据软件主管的限制,我只能使用 Libxml++。

我让一切正常工作,现在尝试进行错误处理,以便返回更有意义的错误消息。在解析错误时,这已经为我完成了,因为它返回发生解析问题的行号和列号。但是,对于有效性异常,它仅说明捕获有效性错误的元素以及有关错误原因的简短消息。

是否可以对其进行修改,使其还返回遇到的行号和列号?问题是,如果针对不唯一的元素捕获了有效性错误,并且 XML 文件有数千行那么长,那么查找它就会变得相当无关紧要。

我使用 DomParser 来解析 XML,并使用 SchemaValidator 类(如 libxml++ 中所示)

最佳答案

据我所知,这对于libxml++是不可能的,但您可以直接使用底层的libxml2函数。关键是用xmlSchemaSetValidStructuredErrors注册一个结构化错误处理程序。 。错误处理程序收到 xmlError其中包含行号和列号的字段。该列存储在 int2 中。请参阅以下示例程序:

#include <stdio.h>
#include <libxml/xmlschemas.h>

void errorHandler(void *userData, xmlErrorPtr error) {
    printf("Error at line %d, column %d\n%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'.

关于c++ - Libxml++ : Returning Line/Column number upon validity errors,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37164353/

相关文章:

c++ - 为什么 std::unique_ptr 阻止访问被销毁的对象?

java - Android 4 设置样式

java - 处理 JAXB 中格式不正确的(数字)元素标签

C++将参数中的函数传递给另一个函数

c++ - C++像初始化一样将数据分配给数组

c# - 用 XML 编写命名空间

c# - 通用通信框架的模式(处理和公开接收到的数据)

validation - JAX-WS RI 不强制执行 XSD 限制

xml - 在 XML XSD 中定义递归代数数据类型

c++ - 哪种数据类型对应于 C++ 中的 10^16?