当attribute1,python,xml时如何获取attribute2值

xiaoxingxing python 219

原文标题how can I get the attribute2 value when attribute1, python, xml

<book>
<propery name= "Hello world", value ="0"/>
<propery name ="I'm new", value ="1"/>

</book>

就像我想在名称“Hello world”时搜索属性,然后打印/修改此元素的值

原文链接:https://stackoverflow.com//questions/71962392/how-can-i-get-the-attribute2-value-when-attribute1-python-xml

回复

我来回复
  • programmer365的头像
    programmer365 评论

    您可以使用 Python 标准库 (xml.etree.elementTree) 中的 XML 解析器:

    s='''<?xml version="1.0" encoding="UTF-8"?>
    <book>
    <propery name="Hello world" value="0"/>
    <propery name="Im new" value 
    ="1"/>
    </book>
    '''
    
    import xml.etree.ElementTree as ET
    myroot = ET.fromstring(s)
    
    for item in myroot:
        if item.attrib["name"] == "Hello world":
            print(item.attrib["value"])
    
    • 首先,您将 XML 作为字符串加载到 s 中。
    • 然后通过 ET.fromString() 将其根元素加载到 myroot 中
    • 循环遍历根元素 book 的子元素
    • 并找到名称为“Hello World”的元素
    • 并输出Value属性
    2年前 0条评论
  • mnzbono的头像
    mnzbono 评论

    我推荐使用 xml 解析器,你的生活会更轻松。我个人使用 xmltodict,但还有其他的。

    如果您只想一次性快速提取,您可以使用正则表达式,例如:

    value = re.search('"Hello world".*?value[^"]*"([^"]*)"', xmltext)

    上面的一个将为您提供您正在寻找的“价值”。我个人更喜欢像下面这样包装正则表达式,所以它不那么麻烦:

    value = (re.findall('"Hello world".*?value[^"]*"([^"]*)"', xmltext) or [None])[0]

    不过,如果您想提取很多,或者修改值并获取 xml,建议使用解析器。

    2年前 0条评论