Skip to content Skip to sidebar Skip to footer

Getting Attribute Of An Element With Its Corresponding Id

suppose that i have this xml file :
<

Solution 1:

You can do it in two lines if you really want to do so.

>>>from lxml import etree>>>tree = etree.parse('public.xml')>>>for item in tree.xpath('.//article[@id]//type[@weight]'):...    item.xpath('../..')[0].attrib['id'], item.attrib['weight']... 
('11234', '0.32')
('63563', '0.86')

One xml checker I used insisted on double-quotes around the values for weight. etree croaked on the xml until I dropped the first line in the file; I don't know why.

Solution 2:

One of these This might work for you:

In this version, note the addition of = in the call to tree.xpath():

from lxml import etree
tree = etree.parse("news.xml")


for article in tree.iter('article'):
    article_id = article.attrib.get('id')

    for weight in tree.xpath("//article[@id={}]/feed/type/@weight".format(article_id)):
        print(article_id,weight)

Here, notice that I replaced tree.xpath() with article.xpath():

from lxml import etree
tree = etree.parse("news.xml")

for article in tree.iter('article'):
    article_id = article.attrib.get('id')

    for weight in article.xpath("./feed/type/@weight"):
        print(article_id,weight)

Post a Comment for "Getting Attribute Of An Element With Its Corresponding Id"