简体   繁体   English

lxml etree xmlparser 删除不需要的命名空间

[英]lxml etree xmlparser remove unwanted namespace

I have an xml doc that I am trying to parse using Etree.lxml我有一个我正在尝试使用 Etree.lxml 解析的 xml 文档

<Envelope xmlns="http://www.example.com/zzz/yyy">
  <Header>
    <Version>1</Version>
  </Header>
  <Body>
    some stuff
  <Body>
<Envelope>

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:当我尝试获取 dom.getroot() 时,我得到:

<Element {http://www.example.com/zzz/yyy}Envelope at 28adacac>

However I only want:但是我只想要:

<Element Envelope at 28adacac>

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.我认为将 ns_clean=True 传递给解析器会阻止这种情况。

Any ideas?有任何想法吗?

import io
import lxml.etree as ET

content='''\
<Envelope xmlns="http://www.example.com/zzz/yyy">
  <Header>
    <Version>1</Version>
  </Header>
  <Body>
    some stuff
  </Body>
</Envelope>
'''    
dom = ET.parse(io.BytesIO(content))

You can find namespace-aware nodes using the xpath method: 您可以使用xpath方法找到名称空间感知节点:

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

If you really want to remove namespaces, you could use an XSL transformation: 如果您确实要删除名称空间,则可以使用XSL转换:

# http://wiki.tei-c.org/index.php/Remove-Namespaces.xsl
xslt='''<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="no"/>

<xsl:template match="/|comment()|processing-instruction()">
    <xsl:copy>
      <xsl:apply-templates/>
    </xsl:copy>
</xsl:template>

<xsl:template match="*">
    <xsl:element name="{local-name()}">
      <xsl:apply-templates select="@*|node()"/>
    </xsl:element>
</xsl:template>

<xsl:template match="@*">
    <xsl:attribute name="{local-name()}">
      <xsl:value-of select="."/>
    </xsl:attribute>
</xsl:template>
</xsl:stylesheet>
'''

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))
# <Envelope>
#   <Header>
#     <Version>1</Version>
#   </Header>
#   <Body>
#     some stuff
#   </Body>
# </Envelope>

So you can now find the Body node this way: 现在,您可以通过以下方式找到“身体”节点:

print(dom.find("Body"))
# <Element Body at 8506cd4>

Try using Xpath: 尝试使用Xpath:

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

Taken (and simplified) from this page , under "The xpath() method" section 摘自(简化) 此页面的 “ xpath()方法”部分下

The last solution from https://bitbucket.org/olauzanne/pyquery/issue/17 can help you to avoid namespaces with little effort 来自https://bitbucket.org/olauzanne/pyquery/issue/17的最后一个解决方案可以帮助您轻松避免命名空间

apply xml.replace(' xmlns:', ' xmlnamespace:') to your xml before using pyquery so lxml will ignore namespaces 在使用pyquery之前将xml.replace(' xmlns:', ' xmlnamespace:')应用于您的xml,以便lxml会忽略名称空间

In your case, try xml.replace(' xmlns="', ' xmlnamespace="') . 在您的情况下,请尝试xml.replace(' xmlns="', ' xmlnamespace="') However, you might need something more complex if the string is expected in the bodies as well. 但是,如果字符串也在主体中,则可能需要更复杂的东西。

Another not-too-bad option is to use the QName helper and wrap it in a function with a default namespace:另一个不错的选择是使用 QName 帮助器并将其包装在具有默认命名空间的函数中:

from lxml import etree

DEFAULT_NS = 'http://www.example.com/zzz/yyy'

def tag(name, ns=DEFAULT_NS):
    return etree.QName(ns, tag)

dom = etree.parse(path)
body = dom.getroot().find(tag('Body'))

You're showing the result of the repr() call. 您正在显示repr()调用的结果。 When you programmatically move through the tree, you can simply choose to ignore the namespace. 当您以编程方式遍历树时,只需选择忽略名称空间即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM