lxml etree xmlparser eliminar espacio de nombres no deseado


Tengo un documento xml que estoy tratando de analizar usando Etree.lxml

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

Mi código es:

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

Cuando trato de conseguir a Dom.getroot() obtengo:

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

Sin embargo, solo quiero:

<Element Envelope at 28adacac>

Cuando lo hago

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

No me devuelven nada. Sin embargo, cuando yo

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

Obtengo un resultado.

Pensé que pasar ns_clean=True al analizador evitaría esto.

¿Alguna idea?

Author: Kenster, 2010-11-23

4 answers

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

Puede encontrar nodos con espacio de nombres usando el método 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>]

Si realmente desea eliminar espacios de nombres, podría usar una transformación 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)

Aquí vemos que el espacio de nombres ha sido eliminado:

print(ET.tostring(dom))
# <Envelope>
#   <Header>
#     <Version>1</Version>
#   </Header>
#   <Body>
#     some stuff
#   </Body>
# </Envelope>

Así que ahora puedes encontrar el nodo del Cuerpo de esta manera:

print(dom.find("Body"))
# <Element Body at 8506cd4>
 49
Author: unutbu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-03 15:18:50

Intenta usar Xpath:

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

Tomado (y simplificado) de esta página , bajo la sección" El método xpath () "

 25
Author: dusan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-02-05 11:45:19

La última solución de https://bitbucket.org/olauzanne/pyquery/issue/17 puede ayudarte a evitar los espacios de nombres con poco esfuerzo

Aplique xml.replace(' xmlns:', ' xmlnamespace:') a su xml antes de usar pyquery para que lxml ignore los espacios de nombres

En su caso, intente xml.replace(' xmlns="', ' xmlnamespace="'). Sin embargo, es posible que necesite algo más complejo si la cadena también se espera en los cuerpos.

 3
Author: Andrei,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-07-01 09:40:52

Estás mostrando el resultado de la llamada repr (). Cuando se mueve programáticamente a través del árbol, simplemente puede elegir ignorar el espacio de nombres.

 -1
Author: robert,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-11-23 11:00:45