【问题标题】:How to add namespace in existing xml file如何在现有的 xml 文件中添加命名空间
【发布时间】:2021-09-27 08:29:31
【问题描述】:

示例 xml:

<abcd>

... Many contents here ...

</abcd>

我想更改如下示例文件:

<abcd xmlns="urn:myname" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                         xsi:schemaLocation="urn:myname myname.xsd">

.... many contents here

</abcd>

所以,我的代码如下,但是当我打印出文档时,结果与输入文件相同。

attr_qname = etree.QName("http://www.w3.org/2001/XMLSchema-instance", "schemaLocation")
nsmap = {None: "urn:myname", 'xsi':"http://www.w3.org/2001/XMLSchema-instance"}
document = etree.parse(self.fname)
root = document.getroot()
root = etree.Element('abcd', {attr_qname: 'urn:myname myname.xsd'}, nsmap=nsmap)
print("Parsed : ", etree.tostring(document, pretty_print=True).decode())

如何添加命名空间并打印出来?

【问题讨论】:

    标签: python python-3.x xml lxml xml-namespaces


    【解决方案1】:

    在您的代码中,您只是创建了一个新的abcd,并且不对其进行任何操作

    试试这个

    attr_qname = etree.QName("http://www.w3.org/2001/XMLSchema-instance", "schemaLocation")
    nsmap = {None: "urn:myname", 'xsi':"http://www.w3.org/2001/XMLSchema-instance"}
    document = etree.parse(self.fname)
    root = document.getroot()
    
    abcd = root.find('abcd')
    abcd.set('xmlns', "urn:myname")
    abcd.set(attr_qname, "urn:myname myname.xsd")
    print("Parsed : ", etree.tostring(root, pretty_print=True).decode())
    

    【讨论】:

      猜你喜欢
      • 2010-10-12
      • 2010-10-30
      • 1970-01-01
      • 1970-01-01
      • 2019-04-14
      • 2011-11-27
      • 1970-01-01
      • 1970-01-01
      • 2018-10-04
      相关资源
      最近更新 更多