我的脚本或XML文件是否有问题?我正在使用ElementTree试图获取子属性

2024-06-07 09:04:02 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我试图解析的XML文件的简短版本:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<TipsContents xmlns="http://www.avendasys.com/tipsapiDefs/1.0">
  <TipsHeader exportTime="Mon May 04 20:05:47 SAST 2020" version="6.8"/>
  <Endpoints>
    <Endpoint macVendor="SHENZHEN RF-LINK TECHNOLOGY CO.,LTD." macAddress="c46e7b2939cb" status="Known">
      <EndpointProfile updatedAt="May 04, 2020 10:02:21 SAST" profiledBy="Policy Manager" addedAt="Mar 04, 2020 17:31:53 SAST" fingerprint="{}" conflict="false" name="Windows" family="Windows" category="Computer" staticIP="false" ipAddress="xxx.xxx.xxx.xxx"/>
      <EndpointTags tagName="Username" tagValue="xxxxxxxx"/>
      <EndpointTags tagName="Disabled Reason" tagValue="IS_ACTIVE"/>
    </Endpoint>
     </Endpoints>
  <TagDictionaries>
    <TagDictionary allowMultiple="false" mandatory="true" defaultValue="false" dataType="Boolean" attributeName="DOMAIN-MACHINES" entityName="Endpoint"/>
    <TagDictionary allowMultiple="false" mandatory="true" defaultValue="true" dataType="Boolean" attributeName="IS_ACTIVE" entityName="Endpoint"/>
    <TagDictionary allowMultiple="true" mandatory="false" dataType="String" attributeName="Disabled Reason" entityName="Endpoint"/>
    <TagDictionary allowMultiple="false" mandatory="false" dataType="String" attributeName="Username" entityName="Endpoint"/>
  </TagDictionaries>
</TipsContents>

我运行以下脚本:

import xml.etree.ElementTree as ET 
f = open("Endpoint-5.xml", 'r')
tree = ET.parse(f)
root = tree.getroot()

我的输出是这样的:


In [8]: root = tree.getroot()                                                                                                                                                                               

In [9]: root.findall('.')                                                                                                                                                                                   
Out[9]: [<Element '{http://www.avendasys.com/tipsapiDefs/1.0}TipsContents' at 0x10874b410>]

In [10]: root.findall('./TipsHeader')                                                                                                                                                                       
Out[10]: []

In [11]: root.findall('./TipsContents')                                                                                                                                                                     
Out[11]: []

In [15]: root.findall('{http://www.avendasys.com/tipsapiDefs/1.0}TipsContents//Endpoints/Endpoint/EndpointProfile')                                                                                         
Out[15]: []

我一直在关注这个:https://docs.python.org/3/library/xml.etree.elementtree.html#example 在其他教程中,我似乎没有得到输出

我试过from lxml import html

我的脚本如下:

        tree = html.fromstring(html=f)
        updatedAt = tree.xpath("//TipsContents/Endpoints/Endpoint/EndpointProfile/@updatedAt")
        name = tree.xpath("//TipsContents/Endpoints/Endpoint/EndpointProfile/@name")
        category = tree.xpath("//TipsContents/Endpoints/Endpoint/EndpointProfile/@category")
        tagValue = tree.xpath("//TipsContents/Endpoints/Endpoint/EndpointTags[@tagName = 'Username']/@tagValue") 
        active = tree.xpath("//TipsContents/Endpoints/Endpoint/EndpointTags[@tagName = 'Disabled Reason']/@tagValue")
        print("Name:",name)

上述尝试也不会返回任何结果

我能够从API解析XML文档并成功地使用第二次尝试,但是当我从本地文件解析XML文档时,我没有得到结果

任何协助都将不胜感激


Tags: nameinfalsetreerootxmlxpathendpoint
1条回答
网友
1楼 · 发布于 2024-06-07 09:04:02

请注意,您的输入XML包含一个默认名称空间,以便参考 必须指定名称空间的任何元素

其中一种方法是定义名称空间字典 (快捷方式全名),在您的情况下:

ns = {'tips': 'http://www.avendasys.com/tipsapiDefs/1.0'}

然后,使用findall

  • 在元素名称(和“:”)之前使用适当的快捷方式
  • 将命名空间字典作为第二个参数传递

执行此操作的代码是:

for elem in root.findall('./tips:TipsHeader', ns):
    print(elem.attrib)

对于您的输入样本,结果是:

{'exportTime': 'Mon May 04 20:05:47 SAST 2020', 'version': '6.8'}

root.findall('./TipsContents')而言,它将返回 空列表,即使您如上所述指定了名称空间

原因是TipsContents根节点的名称, 而您试图在中的下找到同名的元素 XML树,但它不包含这样的元素

如果要访问根元素的属性,可以运行:

print(root.attrib)

但是要得到比空字典更多的东西,你必须添加 根元素的某些属性(命名空间不是属性)

相关问题 更多 >

    热门问题