Get list of XML attribute values in Python

前端 未结 7 1468
有刺的猬
有刺的猬 2020-12-31 07:37

I need to get a list of attribute values from child elements in Python.

It\'s easiest to explain with an example.

Given some XML like this:

&         


        
相关标签:
7条回答
  • 2020-12-31 07:59

    I'm not really an old hand at Python, but here's an XPath solution using libxml2.

    import libxml2
    
    DOC = """<elements>
        <parent name="CategoryA">
            <child value="a1"/>
            <child value="a2"/>
            <child value="a3"/>
        </parent>
        <parent name="CategoryB">
            <child value="b1"/>
            <child value="b2"/>
            <child value="b3"/>
        </parent>
    </elements>"""
    
    doc = libxml2.parseDoc(DOC)
    
    def getValues(cat):
        return [attr.content for attr in doc.xpathEval("/elements/parent[@name='%s']/child/@value" % (cat))]
    
    print getValues("CategoryA")
    

    With result...

    ['a1', 'a2', 'a3']
    
    0 讨论(0)
提交回复
热议问题