gpt4 book ai didi

python - lxml - 元素上元标记的访问值

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

我有以下 XML 元素:

<AdditionalAttribute name="Internal Version Identifier" value="UCV261KSBQGBPYF6" dataType="String"></AdditionalAttribute> 

这些标签有很多,我想专门针对这个标签。一些标签的示例如下:

<AdditionalAttribute name="Version Notes" value="This Item was released indirectly as a result of releasing Item 10X9061-11 to In Design." dataType="String"></AdditionalAttribute>
<AdditionalAttribute name="Change Number" value="BCV2386079506" dataType="String"></AdditionalAttribute>
<AdditionalAttribute name="Version Shared" value="No" dataType="String"></AdditionalAttribute>
<AdditionalAttribute name="Effective Version Shared" value="No" dataType="String"></AdditionalAttribute>
<AdditionalAttribute name="Material Effectivity Date" value="2016-03-15T08:52:33-08:00" dataType="String"></AdditionalAttribute>

<AdditionalAttribute name="Internal Version Identifier" value="UCV261KSBQGBPYF6" dataType="String"></AdditionalAttribute>
<AdditionalAttribute name="Item Creation Date" value="2016-03-01T09:08:14-08:00" dataType="String"></AdditionalAttribute>

我正在使用 lxml 和 xpath 来尝试查询“内部版本标识符”的所有附加属性,一旦我拥有了我需要从“值”字段中提取值的元素。

我想找到名称为“内部版本标识符”的 AdditionalAttribute 元素,然后在“值”字段中获取值。

我一直在尝试一些不同的事情,但无法获得我需要的值(value):

这是我当前的 xpath 查询:

tree.xpath('//AdditionalAttribute[starts-with(text(), "Internal")]')

最佳答案

试试 //AdditionalAttribute[@name="Internal Version Identifier"]

测试示例:

from lxml import etree

tree = etree.XML('''
<root>
<AdditionalAttribute name="Version Notes" value="This Item was released indirectly as a result of releasing Item 10X9061-11 to In Design." dataType="String"></AdditionalAttribute>
<AdditionalAttribute name="Change Number" value="BCV2386079506" dataType="String"></AdditionalAttribute>
<AdditionalAttribute name="Version Shared" value="No" dataType="String"></AdditionalAttribute>
<AdditionalAttribute name="Effective Version Shared" value="No" dataType="String"></AdditionalAttribute>
<AdditionalAttribute name="Material Effectivity Date" value="2016-03-15T08:52:33-08:00" dataType="String"></AdditionalAttribute>

<AdditionalAttribute name="Internal Version Identifier" value="UCV261KSBQGBPYF6" dataType="String"></AdditionalAttribute>
<AdditionalAttribute name="Item Creation Date" value="2016-03-01T09:08:14-08:00" dataType="String"></AdditionalAttribute>
</root>
''')

elements = tree.xpath('//AdditionalAttribute[@name="Internal Version Identifier"]')
assert len(elements) == 1
assert elements[0].attrib["value"] == 'UCV261KSBQGBPYF6'

或者,如果您只对 value 而不是整个元素感兴趣:

elements = tree.xpath(
'//AdditionalAttribute[@name="Internal Version Identifier"]/@value')

assert len(elements) == 1
assert elements[0] == 'UCV261KSBQGBPYF6'

关于python - lxml - 元素上元标记的访问值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36945071/

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