Python:在 xml.etree 元素上指定 XMLNS

标签 python schema xml-namespaces elementtree

在我的 Python 代码中,我目前正在使用 xml.etree 库来创建树,然后将其转储为 XML 字符串。不幸的是,我不能使用 Python 标准库中的模块以外的模块来执行此操作。

这是我的代码:

import xml.etree.ElementTree as ET

def dump_to_XML():
  root_node = ET.Element("root")
  c1_node = ET.SubElement(root_node, "child1")
  c1_node.text = "foo"
  c2_node = ET.SubElement(root_node, "child2")
  gc1_node = ET.SubElement(c2_node, "grandchild1")
  gc1_node.text = "bar"
  return ET.tostring(root_node, encoding='utf8', method='xml')

给出字符串:

<?xml version='1.0' encoding='utf8'?>
<root>
    <child1>foo</child1>
    <child2>
        <grandchild1>bar</grandchild1>
    </child2>
</root>

现在,我有两个架构文件位于 - 比如说 - http://myhost.com/p.xsdhttp://myhost.com/q.xsd,我希望输出字符串变成:

<?xml version='1.0' encoding='UTF-8'?>
<root xmlns:p="http://myhost.com/p.xsd" xmlns:q="http://myhost.com/q.xsd">
    <p:child1>foo</p:child1>
    <p:child2>
        <q:grandchild1>bar</q:grandchild1>
    </p:child2>
</root>

如何利用 etree 库来实现这一目标?

提前致谢

最佳答案

开始吧:

import xml.etree.ElementTree as ET

xmlns_uris = {'p': 'http://myhost.com/p.xsd',
              'q': 'http://myhost.com/q.xsd'}

def dump_to_XML():
  root_node = ET.Element("root")
  c1_node = ET.SubElement(root_node, "child1")
  c1_node.text = "foo"
  c2_node = ET.SubElement(root_node, "child2")
  gc1_node = ET.SubElement(c2_node, "grandchild1")
  gc1_node.text = "bar"
  annotate_with_XMLNS_prefixes(gc1_node, 'q', False)
  annotate_with_XMLNS_prefixes(root_node, 'p')
  add_XMLNS_attributes(root_node, xmlns_uris)
  return ET.tostring(root_node, encoding='UTF-8', method='xml')

def annotate_with_XMLNS_prefixes(tree, xmlns_prefix, skip_root_node=True):
    if not ET.iselement(tree):
        tree = tree.getroot()
    iterator = tree.iter()
    if skip_root_node: # Add XMLNS prefix also to the root node?
        iterator.next()
    for e in iterator:
        if not ':' in e.tag:
            e.tag = xmlns_prefix + ":" + e.tag

def add_XMLNS_attributes(tree, xmlns_uris_dict):
    if not ET.iselement(tree):
        tree = tree.getroot()
    for prefix, uri in xmlns_uris_dict.items():
        tree.attrib['xmlns:' + prefix] = uri

执行:print dump_to_XML() 给出:

<?xml version='1.0' encoding='UTF-8'?>
<root xmlns:p="http://myhost.com/p.xsd" xmlns:q="http://myhost.com/q.xsd">
    <p:child1>foo</p:child1>
    <p:child2>
        <q:grandchild1>bar</q:grandchild1>
    </p:child2>
</root>

关于Python:在 xml.etree 元素上指定 XMLNS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22039115/

相关文章:

python - 生成缓冲区半径多边形 - 可能的投影问题

Python - 如何检查列表单调性

xml - 当我包含 xmlns ="http://www.sitemaps.org/schemas/sitemap/0.9"时,XSLT 不起作用

XML - 命名空间

java - 为标记 LinearLayout (xmlns :tools ERROR)) 找到意外的命名空间前缀 "xmlns"

python - 在 aiohttp 中使用共享 TCPConnector 时出错

python - 在Python中使用正则表达式分割罗马数字

node.js - 如何处理 Mongoose 中的 ENUM 值?

Oracle:仅导出模式

python - python中的数据格式二进制模式描述和解码