gpt4 book ai didi

Python 读取 XML 子级

转载 作者:太空宇宙 更新时间:2023-11-03 15:49:38 24 4
gpt4 key购买 nike

尝试解析此 XML,但我似乎无法弄清楚哪里出了问题。

XML 片段:

<thexml timestamp="2017-01-02T10:17:41">
<event="41" date="2017-04-01" id="5543" time="09:30:00" type="seat" link="na"></event>
</thexml>

我正在尝试:

DOMTree = parseString(response.content)
collection = DOMTree.documentElement
selections = collection.getElementsByTagName("event")
for select in selections:
print "event found"

这似乎可以触发 XML 中的事件。例如,试图获取类型,这种格式让我很困惑。

tags = select.getElementsByTagName("type")

当我使用它时,标签的字符串会变成表明它找到了它。但我不确定如何实际读取 child 的字符串。我一直在尝试以下方面的变体:

print type.childNodes[0].data
print type.childNodes.data
print type.data

我在这里遗漏了一些非常明显的东西吗?我解析了一堆 XML,但这种格式让我有点困惑。希望能指出正确的方向。

最佳答案

您的 xml 中仍然存在问题。

这是修复方法(以及如何提取相关属性):

In [17]: c = """<thexml timestamp="2017-01-02T10:17:41">
...: <event date="2017-04-01" id="5543" time="09:30:00" type="seat" link="na"></event>
...: </thexml>
...: """
In [18]: DOMTree = parseString(c)
In [19]: collection = DOMTree.documentElement
In [20]: s = collection.getElementsByTagName('event')
In [21]: for e in s:
...: print(e.getAttribute('type'))
...:
seat

Note that in your example - type is an Attribute (And not Node) so you can't use getElementsByTagName("type"), you will need to use getAttribute

关于Python 读取 XML 子级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41426036/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com