【问题标题】:python iterate xml avoiding namespacepython迭代xml避免命名空间
【发布时间】:2020-05-13 16:58:04
【问题描述】:

使用我的 python 脚本,我想迭代我的 xml 文件以搜索特定的元素标记。 我有一些与根标签的命名空间有关的问题。

在我的 XML 结构下:

<?xml version="1.0" ?>
<rootTag xmlns="blablabla">
    <tag_1>
        <sub_tag_1>..something..</sub_tag_1>
    </tag_1>
    <tag_2>
        <sub_tag_2>..something..</sub_tag_2>
    </tag_2>
    ...and so on...
</rootTag>

在我的 PYTHON 脚本下方:

import xml.etree.ElementTree as ET

root = ET.fromstring(xml_taken_from_web)
print(root.tag)

问题是 print 的输出是:

{blablabla}根标签

所以当我遍历它时,所有 tag_1、tag_2 等标签都会有 {blablabla} 字符串,所以我无法对标签进行任何检查。

我试过用这种方式使用正则表达式

root = re.sub('^{.*?}', '', root.tag)

问题是之后的根是字符串类型,所以我不能超过它这样的元素类型

我怎样才能只打印 rootTag ?

【问题讨论】:

    标签: python xml xml-namespaces


    【解决方案1】:

    只要使用:

    import xml.etree.ElementTree as ET
    from lxml import etree
    
    root = ET.fromstring(xml_taken_from_web)
    print(etree.QName(root.tag).localname)
    

    【讨论】:

    • 这样,root 将是一个字符串,因此无法在搜索嵌套标签时对其进行迭代。
    • 我收到错误 AttributeError: module 'xml.etree' has no attribute 'QName'
    • @xXJohnRamboXx 已编辑重试
    • 现在代码运行但我得到这个输出错误:ValueError: Invalid tag name ""
    • @xXJohnRamboXx 奇怪的再试一次
    猜你喜欢
    • 2017-06-11
    • 2019-05-11
    • 1970-01-01
    • 2016-02-18
    • 1970-01-01
    • 2020-01-03
    • 1970-01-01
    • 1970-01-01
    • 2011-08-16
    相关资源
    最近更新 更多