【问题标题】:Python reading xmlPython读取xml
【发布时间】:2021-07-26 23:13:54
【问题描述】:

我是 Python 编程的新手。我有一个要求,我需要读取 xml 结构并通过添加命名空间来构建新的 soap 请求 xml,如下所示是我所拥有的示例

下面是我从其他系统获得的 XML:

<foo>
   <bar>
      <type foobar="1"/>
      <type foobar="2"/>
   </bar>
</foo>

我想要如下的最终结果

<?xml version="1.0"?>
<soa:foo xmlns:soa="https://www.w3schools.com/furniture">
   <soa:bar>
      <soa:type foobar="1"/>
      <soa:type foobar="2"/>
   </soa:bar>
</soa:foo>

我试图在 python document 中查找但找不到

【问题讨论】:

  • 我更新了代码格式并尝试修复输出。请看一看,确保那是你真正想要的。你看过 ElementTree 或 lxml 吗?
  • 你的意思是什么文档?显示有问题的链接(不在评论中)。您使用什么模块 - 标准xml,或外部lxmlBeautifulsoup,或其他。
  • @furas 我正在尝试在 Python 中找到读取 xml 并提供上述所需输出的示例。

标签: python python-3.x


【解决方案1】:

一种选择是使用 lxml 遍历所有元素并将命名空间 uri 添加到 .tag 属性。

您可以使用register_namespace() 将uri 绑定到所需的前缀。

示例...

from lxml import etree

tree = etree.parse("input.xml")

etree.register_namespace("soa", "https://www.w3schools.com/furniture")

for elem in tree.iter():
    elem.tag = f"{{https://www.w3schools.com/furniture}}{elem.tag}"

print(etree.tostring(tree, pretty_print=True).decode())

打印输出...

<soa:foo xmlns:soa="https://www.w3schools.com/furniture">
   <soa:bar>
      <soa:type foobar="1"/>
      <soa:type foobar="2"/>
   </soa:bar>
</soa:foo>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-20
    • 2014-03-14
    • 2020-10-18
    • 1970-01-01
    • 2013-05-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多