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

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

问题描述

我有一个我正在尝试使用 Etree.lxml 解析的 xml 文档

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>

所以你现在可以通过这种方式找到 Body 节点:

So you can now find the Body node this way:

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

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

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