开发者

ElementTree XPath strange behaviour

开发者 https://www.devze.com 2023-02-11 02:01 出处:网络
Hi I\'m using ElementTree (1.3) with Python 2.7 and enjoy XPath functionality, however one of search results surprised me.

Hi

I'm using ElementTree (1.3) with Python 2.7 and enjoy XPath functionality,

however one of search results surprised me.

My XML example:

<OTF>
  <FECS state="disabled" version="2.2.0.0">
    <BackEndCompatibility major="2.2" state="disabled">
        <BackEnd state="disabled" version="2.2.0.0"/>
    </BackEndCompatibility>
  </FECS>
</OTF>

Question 1:

When I use findall to get first found element

version = "2.2.0.0"
found = list(txml.findall(".//BackEnd[@version='%s']" % version))
return found and found[0] or None

it fi开发者_StackOverflownds nothing.

However when I change XML file, so that BackEnd element contains subelements,

        <BackEnd state="disabled" version="2.2.0.0">
           <any_dummy_element/> 
        </BackEnd>

then searched element is found properly.

Did you face such a behaviour?

Am I doing sth wrong or this is a bug in ElementTree implementation?

Question 2:

Another issue I have is xmlns.

Let's assume I change XML first line to contain xmlns:

<OTF xmlns="http://si-wiki/OTFCompatibility">
</OTF>

In such a case I have to change find string to:

".//{http://si-wiki/OTFCompatibility}BackEnd[@version='%s']"

Is there any way to tell ElementTree to ignore xmlns during parsing and treat all elements' names (including root) like they had no prefix?

Regards,

Zbigniew


For question No1:
When I replaced lines

    found = list(txml.findall(".//BackEnd[@version='%s']" % version))
    return found and found[0] or None

with

    found = txml.findall(".//BackEnd[@version='%s']" % version)
    if found:
        return found[0]
    return None

then correct result is returned without dummy children hack.

0

精彩评论

暂无评论...
验证码 换一张
取 消