gpt4 book ai didi

c - libxml2 错误 : validation of in-memory doc in C

转载 作者:行者123 更新时间:2023-11-30 17:09:27 25 4
gpt4 key购买 nike

我在 libxml2 中遇到验证问题,因为 xmlSchemaValidateDoc 失败并出现以下错误:

Element '{http://evcom.dk}cdr', attribute 'xmlns:xs': The attribute 
'xmlns:xs' is not allowed.
Element '{http://evcom.dk}cdr', attribute 'xmlns:tns': The attribute
'xmlns:tns' is not allowed.

使用 xmllint 时生成的 xml 文件会进行验证,经过一番解决后,我发现如果我在验证之前保存并读回 xml 文档,该文件也会验证。

换句话说,使用(简化的 - 没有错误检查)代码:

char *path = "/home/dev/cdr.xml";
char *namespace = "http://evcom.dk";
xmlDocPtr pDoc = xmlNewDoc(BAD_CAST "1.0");
xmlNsPtr tns = xmlNewNs(NULL, BAD_CAST namespace, BAD_CAST "tns");
xmlNodePtr xnpRoot = xmlNewNode(tns, BAD_CAST "cdr");
xmlNewProp(xnpRoot, BAD_CAST "xmlns:xs",
BAD_CAST "http://www.w3.org/2001/XMLSchema");
xmlNewProp(xnpRoot, BAD_CAST "xmlns:tns", BAD_CAST namespace);
xmlDocSetRootElement(pDoc, xnpRoot);
xmlNodePtr xnpChild1 = xmlNewChild(xnpRoot, tns, BAD_CAST "test", NULL);
xmlAddChild(xnpChild1, xmlNewText(BAD_CAST "TEST"));
xmlSaveFormatFileEnc(path, pDoc, "UTF-8", 1);
//xmlFreeDoc(pDoc);
//pDoc = xmlReadFile(path, NULL, XML_PARSE_NONET);
char *schemaPath = "/home/dev/cdr.xsd";
xmlDocPtr pSchemaDoc = xmlReadFile(schemaPath, NULL, XML_PARSE_NONET);
xmlSchemaParserCtxtPtr pParser = xmlSchemaNewDocParserCtxt(pSchemaDoc);
xmlSchemaPtr pSchema = xmlSchemaParse(pParser);
xmlSchemaValidCtxtPtr pSchemaCtxt = xmlSchemaNewValidCtxt(pSchema);
xmlSchemaSetValidErrors(pSchemaCtxt, NULL, NULL, NULL);
xmlSchemaValidateDoc(pSchemaCtxt, pDoc);

该文档不会验证,但如果我取消注释“char *schemaPath”行之前的两行,该文档就会验证。

已发现此问题存在于 x86 和 arm linux 32 位平台上,libxml 版本为 2.9.1 和 2.9.2,使用预编译或我自己编译的库版本。

有人可以透露一些信息吗?

供引用,xsd 文件:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema targetNamespace="http://evcom.dk"
elementFormDefault="qualified"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:tns="http://evcom.dk">
<xs:element name="cdr">
<xs:complexType>
<xs:sequence>
<xs:element name="test">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:minLength value="1"/>
<xs:maxLength value="9"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>

生成的xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<tns:cdr xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:tns="http://evcom.dk">
<tns:test>TEST</tns:test>
</tns:cdr>

最佳答案

切勿使用 xmlNewProp 添加命名空间。此函数只能用于属性。使用 xmlNewNs 添加命名空间声明。更换线路

xmlNewProp(xnpRoot, BAD_CAST "xmlns:xs", 
BAD_CAST "http://www.w3.org/2001/XMLSchema");
xmlNewProp(xnpRoot, BAD_CAST "xmlns:tns", BAD_CAST namespace);

xmlNewNs(xnpRoot, BAD_CAST "http://www.w3.org/2001/XMLSchema",
BAD_CAST "xs");

(xmlns:tns 声明是隐式添加的。)

关于c - libxml2 错误 : validation of in-memory doc in C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33276327/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com