【发布时间】:2012-10-02 16:09:15
【问题描述】:
我有一些由可能有也可能没有空元素的脚本生成的 XML。有人告诉我,现在 XML 中不能有空元素。这是一个例子:
<customer>
<govId>
<id>@</id>
<idType>SSN</idType>
<issueDate/>
<expireDate/>
<dob/>
<state/>
<county/>
<country/>
</govId>
<govId>
<id/>
<idType/>
<issueDate/>
<expireDate/>
<dob/>
<state/>
<county/>
<country/>
</govId>
</customer>
输出应如下所示:
<customer>
<govId>
<id>@</id>
<idType>SSN</idType>
</govId>
</customer>
我需要删除所有空元素。您会注意到,我的代码取出了“govId”子元素中的空白内容,但第二次没有取出任何内容。我目前正在使用 lxml.objectify。
这基本上是我正在做的事情:
root = objectify.fromstring(xml)
for customer in root.customers.iterchildren():
for e in customer.govId.iterchildren():
if not e.text:
customer.govId.remove(e)
有没有人知道用 lxml objectify 做到这一点的方法,或者有更简单的方法吗?如果它的所有元素都是空的,我还想完全删除第二个“govId”元素。
【问题讨论】:
-
您说“您会注意到我的代码取出了“govId”子元素中的空内容,但第二次没有取出任何内容。 ” 你指的是什么“空的东西”?我很困惑;您显示输入或输出的 XML 是什么?
-
@mzjn 我也对此感到困惑。我认为这是他已经得到的输出,但还不正确。
-
@mzjn - 我指的是空元素。我应该删除我找到的任何空元素。我刚刚更新它以显示输入和输出。我会放入整个示例,但由于隐私问题以及真正的 XML 有数百行长这一事实,我不允许这样做。