Home > Software engineering >  how can I get the attribute2 value when attribute1, python, xml
how can I get the attribute2 value when attribute1, python, xml

Time:04-22

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

</book>

Like I want to search the propery when name'Hello world", then print/modify the value of this element

CodePudding user response:

You can use the XML parser from Python Standard Library (xml.etree.elementTree):

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"])
  • First you load the XML into s as string.
  • Then load its root element into myroot through ET.fromString()
  • Loop over the children of root element book
  • And find which element has name "Hello World"
  • And output Value attribute

CodePudding user response:

I recomend using an xml parser, your life will be easier. I personally use xmltodict, but there are others.

If you just want to do a one off quick extraction you may use regex, something like:

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

The above one will get you the "value" you are looking for. I personally prefer to wrap regex something like the below, so it's less hassle:

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

Still, a parser is recommended if you want to extract many, or modify the value and get xml back.

  • Related