python xml.etree.ElementTree模块无法找到特定标签

时间:2018-07-14 04:43:53

标签: python xml python-2.7 elementtree

(1)第一种情况

tomcat-users.xml文件如下

<?xml version="1.0" encoding="UTF-8"?>
<tomcat-users xmlns="http://tomcat.apache.org/xml"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://tomcat.apache.org/xml tomcat-users.xsd"
          version="1.0">
    <role rolename="tomcat"/>
    <role rolename="manager-script"/>
    <role rolename="manager-gui"/>
    <user username="tomcat" password="tomcat" roles="tomcat"/>
    <user username="admin" password="admin" roles="manager-gui"/>
    <user username="admin1" password="admin1" roles="manager-script"/>
    <user username="bob" password="password" roles="apressuser"/>
</tomcat-users>

从上面的tomcat-users.xml文件中,我试图使用python xml查找操作来查找第一个用户标签,如下所示,但未获得预期的输出结果

In [1]: from xml.etree import ElementTree as ET
In [2]: tcusers = ET.parse('tomcat-users.xml')
In [3]: tcusers
Out[3]: <xml.etree.ElementTree.ElementTree at 0x7fcb19434a10>
In [4]: first_user = tcusers.find('./user')
In [5]: first_user
In [6]:

(2)第二种情况

现在如下更改了tomcat-users.xml文件,删除了tomcat-users标记的属性

<?xml version="1.0" encoding="UTF-8"?>
<tomcat-users>
  <role rolename="tomcat"/>
  <role rolename="manager-script"/>
  <role rolename="manager-gui"/>
  <user username="tomcat" password="tomcat" roles="tomcat"/>
  <user username="admin" password="admin" roles="manager-gui"/>
  <user username="admin1" password="admin1" roles="manager-script"/>
  <user username="bob" password="password" roles="apressuser"/>
</tomcat-users>

在这种情况下,我执行了与第一种情况相同的操作来找出用户标签,并获得了成功输出

In [7]: tcusers = ET.parse('tomcat-users.xml')
In [8]: tcusers
Out[8]: <xml.etree.ElementTree.ElementTree at 0x7fcb19440850>
In [9]: first_user = tcusers.find('./user')
In [10]: first_user
Out[10]: <Element 'user' at 0x7fcb19440a10>
In [12]: first_user.attrib
Out[12]: {'password': 'tomcat', 'roles': 'tomcat', 'username': 'tomcat'}

所以我的问题是,为什么在第一种情况下具有额外属性xml.etree.ElementTree的find函数无法找到结果?或可能是需要查找的任何其他正则表达式,我也尝试使用*,/,//等,但未得到结果。

请告知,谢谢。

0 个答案:

没有答案