如何从 lxml 树中剥离名称空间?
How can I strip namespaces out of an lxml tree?
从 开始...
感谢@Tichodroma,我有这个代码:
如果可以使用 lxml,试试这个:
import lxml.etree
tree = lxml.etree.parse("leg.xml")
for dog in tree.xpath("//Leg1:Dog",
namespaces={"Leg1": "http://what.not"}):
parent = dog.xpath("..")[0]
parent.remove(dog)
parent.text = None
tree.write("leg.out.xml")
现在 leg.out.xml
看起来像这样:
<?xml version="1.0"?>
<Leg1:MOR xmlns:Leg1="http://what.not" oCount="7">
<Leg1:Order>
<Leg1:CTemp id="FO">
<Leg1:Group bNum="001" cCount="4"/>
<Leg1:Group bNum="002" cCount="4"/>
</Leg1:CTemp>
<Leg1:CTemp id="GO">
<Leg1:Group bNum="001" cCount="4"/>
<Leg1:Group bNum="002" cCount="4"/>
</Leg1:CTemp>
</Leg1:Order>
</Leg1:MOR>
如何修改我的代码以从所有元素的标签名称中删除 Leg1:
命名空间前缀?
从每个元素中删除名称空间前缀的一种可能方法:
def strip_ns_prefix(tree):
#iterate through only element nodes (skip comment node, text node, etc) :
for element in tree.xpath('descendant-or-self::*'):
#if element has prefix...
if element.prefix:
#replace element name with its local name
element.tag = etree.QName(element).localname
return tree
另一个版本在 xpath 中进行命名空间检查,而不是使用 if
语句:
def strip_ns_prefix(tree):
#xpath query for selecting all element nodes in namespace
query = "descendant-or-self::*[namespace-uri()!='']"
#for each element returned by the above xpath query...
for element in tree.xpath(query):
#replace element name with its local name
element.tag = etree.QName(element).localname
return tree
从
感谢@Tichodroma,我有这个代码:
如果可以使用 lxml,试试这个:
import lxml.etree
tree = lxml.etree.parse("leg.xml")
for dog in tree.xpath("//Leg1:Dog",
namespaces={"Leg1": "http://what.not"}):
parent = dog.xpath("..")[0]
parent.remove(dog)
parent.text = None
tree.write("leg.out.xml")
现在 leg.out.xml
看起来像这样:
<?xml version="1.0"?>
<Leg1:MOR xmlns:Leg1="http://what.not" oCount="7">
<Leg1:Order>
<Leg1:CTemp id="FO">
<Leg1:Group bNum="001" cCount="4"/>
<Leg1:Group bNum="002" cCount="4"/>
</Leg1:CTemp>
<Leg1:CTemp id="GO">
<Leg1:Group bNum="001" cCount="4"/>
<Leg1:Group bNum="002" cCount="4"/>
</Leg1:CTemp>
</Leg1:Order>
</Leg1:MOR>
如何修改我的代码以从所有元素的标签名称中删除 Leg1:
命名空间前缀?
从每个元素中删除名称空间前缀的一种可能方法:
def strip_ns_prefix(tree):
#iterate through only element nodes (skip comment node, text node, etc) :
for element in tree.xpath('descendant-or-self::*'):
#if element has prefix...
if element.prefix:
#replace element name with its local name
element.tag = etree.QName(element).localname
return tree
另一个版本在 xpath 中进行命名空间检查,而不是使用 if
语句:
def strip_ns_prefix(tree):
#xpath query for selecting all element nodes in namespace
query = "descendant-or-self::*[namespace-uri()!='']"
#for each element returned by the above xpath query...
for element in tree.xpath(query):
#replace element name with its local name
element.tag = etree.QName(element).localname
return tree