简体   繁体   English

程序在文件中找不到xml数据

[英]Program can't find xml data in file

My code (Python3) is supposed to print COLOR:Red│. 我的代码(Python3)应该打印出COLOR:Red│。 When I run it, it doesn't give me an error message, it doesnt print anything. 当我运行它时,它不会显示错误消息,也不会显示任何内容。 Here is my code and below is the xml file where the data is located: 这是我的代码,下面是数据所在的xml文件:

import os, csv
from xml.etree import ElementTree

file_name = 'data.xml'
full_file = os.path.abspath(os.path.join('xml', file_name))
dom = ElementTree.parse(full_file)

attri = dom.findall('attribute')
lst = []

for c in attri:
    name = c.find('name').text
    value = c.find('value').text
    lst = (name + ':' + value)
    print(lst, end = "│") 



<?xml version="1.0"?>
<all>
<items>
<item>
<attributes>
<attribute>
<name>COLOR</name>
<value>Red</value>
</attributes>
</attribute>
</item>
</items>
</all>

attri = dom.findall('attribute') is returning no results. attri = dom.findall('attribute')未返回任何结果。

The section of the docs titled Finding interesting elements notes that 文档标题为“ 寻找有趣的元素”的部分指出:

Element.findall() finds only elements with a tag which are direct children of the current element. Element.findall()仅查找带有标签的元素,这些标签是当前元素的直接子元素。

But that 但是那

More sophisticated specification of which elements to look for is possible by using XPath . 使用XPath可以更精确地指定要查找的元素。

The simplest fix would be to change your code to 最简单的解决方法是将您的代码更改为

for c in dom.findall('.//attribute'):
    name = c.find('.//name').text
    value = c.find('.//value').text
    print(name + ':' + value, end="│")

See Supported XPath syntax for more information. 有关更多信息,请参见支持的XPath语法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM