可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I have an xml doc that I am trying to parse using Etree.lxml
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='''\ 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)) # # # # 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.