0
我有以下python腳本:如何從具有不同命名空間的孩子獲取lxml.objectify項目?
from lxml import objectify
xml = objectify.fromstring("""<?xml version="1.0" encoding="utf-8"?>
<cfdi:Comprobante xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:cfdi="http://www.sat.gob.mx/cfd/3" xsi:schemaLocation="http://www.sat.gob.mx/cfd/3 http://www.sat.gob.mx/sitio_internet/cfd/3/cfdv32.xsd">
<cfdi:Emisor rfc="XYZU8801017YA" nombre="MOYLOP260">
<cfdi:DomicilioFiscal calle="Calle value"/>
<cfdi:RegimenFiscal Regimen="Regimen value" />
</cfdi:Emisor>
<cfdi:Complemento>
<tfd:TimbreFiscalDigital xsi:schemaLocation="http://www.sat.gob.mx/TimbreFiscalDigital http://www.sat.gob.mx/TimbreFiscalDigital/TimbreFiscalDigital.xsd" xmlns:tfd="http://www.sat.gob.mx/TimbreFiscalDigital"
version="1.0" UUID="UUID value"/>
</cfdi:Complemento>
</cfdi:Comprobante>""")
print "xml.Emisor.DomicilioFiscal.get('calle'):", xml.Emisor.DomicilioFiscal.get('calle')
print "xml.Emisor.RegimenFiscal.get('Regimen'):", xml.Emisor.RegimenFiscal.get('Regimen')
tfd = xml.Complemento.xpath('tfd:TimbreFiscalDigital[1]',
namespaces={'tfd': 'http://www.sat.gob.mx/TimbreFiscalDigital'})
print "tfd[0].get('UUID'):", tfd[0].get('UUID')
try:
print "xml.Complemento.TimbreFiscalDigital: ", xml.Complemento.TimbreFiscalDigital.get('UUID')
except AttributeError:
print "Why I have a AttributeError here?"
輸出是:
xml.Emisor.DomicilioFiscal.get('calle'): Calle value
xml.Emisor.RegimenFiscal.get('Regimen'): Regimen value
tfd[0].get('UUID'): UUID value
xml.Complemento.TimbreFiscalDigital: Why I have a AttributeError here?
我需要得到的最後一個節點的值UUID,但我不喜歡使用硬編碼XML命名空間來自xpath,因爲這是從xml字符串定義的。
你能幫我嗎?謝謝!
我是否需要更新兒童的名稱空間?