如何在python中使用ElementTree获得名称空间为字符串的xml元素?

2024-06-16 18:42:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要从xml中获取字符串形式的元素。我正在尝试下面的xml格式。在

<xml>
    <prot:data xmlns:prot="prot">
        <product-id-template>
            <prot:ProductId>PRODUCT_ID</prot:ProductId>
        </product-id-template>

        <product-name-template>
            <prot:ProductName>PRODUCT_NAME</prot:ProductName>
        </product-name-template>

        <dealer-template>
            <xsi:Dealer xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">DEALER</xsi:Dealer>
        </dealer-template>
    </prot:data>
</xml>

我尝试了以下代码:

^{pr2}$

实际产量:

<ns0:ProductId xmlns:ns0="prot">PRODUCT_ID</ns0:ProductId>

预期产量:

<prot:ProductId>PRODUCT_ID</prot:ProductId>

我不应该从文档中删除它在文档中出现的xmlns。必须把它从没有出现的地方移走。示例product-id-template不包含xmlns,因此需要在不包含xmln的情况下检索它。并且dealer-template包含xmlns,因此需要使用xmlns检索它。在

如何做到这一点?在


Tags: nameiddatatemplatexmlproductdealerxmlns
1条回答
网友
1楼 · 发布于 2024-06-16 18:42:47

您可以使用regex删除xmlns。在

import re
# ...
with_ns = ET.tostring(aa).decode()
no_ns = re.sub(' xmlns(:\w+)?="[^"]+"', '', with_ns)
print(no_ns)

更新:你可以做一件非常疯狂的事情。尽管我不能推荐它,因为我不是Python专家。在

我刚刚检查了源代码,发现我可以做这个黑客:

^{pr2}$

我刚刚定义了my_serialize_xml,它用namespaces=None调用{}。然后,在字典ElementTree._serialize中,我将键"xml"的值改为my_serialize_xml。所以当您调用ElementTree.tostring时,它将使用my_serialize_xml。在

如果您想尝试,只需将上面的代码放在from xml.etree import ElementTree as ET之后(但在使用ET之前)。在

相关问题 更多 >