lxml etree xmlparser删除不需要的名称空间 [英] lxml etree xmlparser remove unwanted namespace

查看:76
本文介绍了lxml etree xmlparser删除不需要的名称空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个XML文档,我正在尝试使用Etree.lxml进行解析

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

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

我的代码是:

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

当我尝试获取dom.getroot()时,我得到:

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

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

但是我只想要:

<Element Envelope at 28adacac>

当我这样做

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

我什么也没得到.但是,当我

I get nothing returned. However, when I

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

我得到一个结果.

我认为将ns_clean = True传递给解析器会阻止这种情况.

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

有什么想法吗?

推荐答案

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))

您可以使用xpath方法找到可识别名称空间的节点:

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)
# [<Element {http://www.example.com/zzz/yyy}Body at 90b2d4c>]

如果您确实要删除名称空间,则可以使用XSL转换:

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

# 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>

这篇关于lxml etree xmlparser删除不需要的名称空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆