本文介紹了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 刪除不需要的命名空間的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!