lxml etree xmlparser remove unwanted namespace

匿名 (未验证) 提交于 2019-12-03 08:28:06

问题:

I have an xml doc that I am trying to parse using Etree.lxml

1
some stuff

My code is:

path = "path to xml file" from lxml import etree as ET parser = ET.XMLParser(ns_clean=True) dom = ET.parse(path, parser) dom.getroot() 

When I try to get dom.getroot() I get:

However I only want:

When i do

dom.getroot().find("Body") 

I get nothing returned. However, when I

dom.getroot().find("{http://www.example.com/zzz/yyy}Body")  

I get a result.

I thought passing ns_clean=True to the parser would prevent this.

Any ideas?

回答1:

import io import lxml.etree as ET  content='''\ 
1
some stuff
''' dom = ET.parse(io.BytesIO(content))

You can find namespace-aware nodes using the xpath method:

body=dom.xpath('//ns:Body',namespaces={'ns':'http://www.example.com/zzz/yyy'}) print(body) # [] 

If you really want to remove namespaces, you could use an XSL transformation:

# http://wiki.tei-c.org/index.php/Remove-Namespaces.xsl xslt=''' '''  xslt_doc=ET.parse(io.BytesIO(xslt)) transform=ET.XSLT(xslt_doc) dom=transform(dom) 

Here we see the namespace has been removed:

print(ET.tostring(dom)) #  #   
# 1 #
# # some stuff # #

So you can now find the Body node this way:

print(dom.find("Body")) # 


回答2:

Try using Xpath:

dom.xpath("//*[local-name() = 'Body']") 

Taken (and simplified) from this page, under "The xpath() method" section



回答3:

The last solution from https://bitbucket.org/olauzanne/pyquery/issue/17 can help you to avoid namespaces with little effort

apply xml.replace(' xmlns:', ' xmlnamespace:') to your xml before using pyquery so lxml will ignore namespaces

In your case, try xml.replace(' xmlns="', ' xmlnamespace="'). However, you might need something more complex if the string is expected in the bodies as well.



回答4:

You're showing the result of the repr() call. When you programmatically move through the tree, you can simply choose to ignore the namespace.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!