如何处理 xml 中的可空值?

How can I handle nillable values in xml?

我编写了一个 Python 脚本,允许将 csv 文件解析为 xml 文件xsd 模式文件。使用 lxml.etreeXMLSchema 方法根据 xsd 模式验证输出 xml 文件。

我目前正在处理缺失值,方法是用虚拟数字 (-999) 替换它们,as detailed in this question,但最近我收到了一个新的 xsd 文件,允许 nillable 个元素:

<xs:element name="ProfileValue" type="xs:double" nillable="true"/>

1. 之后,我尝试使用 xml_data.append('<ProfileValue xsi:nil="true"/>') 将“缺失”值传递给 xml 文件,但这导致以下错误:

Namespace prefix xsi for nil on ProfileValue is not defined

2.看完那个,我也试了xml_data.append('<ProfileValue xs:nil="true"/>'),果然,这个也returns一个XMLSyntaxError:

Namespace prefix xs for nil on ProfileValue is not defined

3. 我尝试省略前缀 (xml_data.append('<ProfileValue nil="true"/>')) ,但这会导致此错误:

Element 'ProfileValue': '' is not a valid value of the atomic type 'xs:double'.

4. 我也试过 xml_data.append('<ProfileValue nil="true"> </ProfileValue>') 按照这个 SO post,但也有一个错误:

Element 'ProfileValue': ' ' is not a valid value of the atomic type 'xs:double'.

我在这里做错了什么?甚至可以将 double 类型值设置为 nillable 吗?

感谢您提供出色的问题描述,并感谢您解释您已经尝试过的所有内容。

我觉得你有两个问题

  1. 您正在使用命名空间前缀 'xsi' 但您没有声明该命名空间。这就像在 C/Java 中使用变量而不先声明它一样。您需要在输出 XML 中包含一个 xmlns 属性(或 'namespace declaration')。像这样:xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"。它可以包含在每个使用 xsi:nil 的标签中,但它通常在根标签上声明一次,从而避免多次声明 xsi 命名空间。

  2. 您正在使用字符串操作构建输出 XML。那可以工作,但前提是你保持幸运。由于您显然可以访问 lxml 库,我强烈建议您允许 lxml 为您执行所有 XML 语法(请参阅 LXML namespaces)。 如果您继续当前路径,您将需要处理 XML 保留 XML 字符、非法 XML 字符等的转义规则。