Murali
Murali

Reputation: 1114

Get parent attributes based on the text of particular tag - XML

I have a XML file which is as follows:

<customer>
     <customerdetails id="80">
         <account id="910">
             <attributes>
                      <premium>true</premium>
                      <type>mpset</type>
             </attributes>
         </account>
         <account id="911">
             <attributes>
                      <premium>true</premium>
                      <type>spset</type>
             </attributes>
         </account>
     </customerdetails>
</customer>

Need to parse the file and get the necessary details from the same, For that I have used python's lxml library.

Using that I can be able to get the details from the XML file, For example I can be able to get the text from the particular tag of the file.

from lxml import etree
    def read_a_customer_section(self):

        root = self.parser.getroot()
        customer_id = "80"
        account_id = "910"
        type_details = root.findtext("customerdetails[@id='"+customer_id+"']/account[@id='"+account_id+"']/attributes/type")
        print type_details

dd = ConfigParserLxml("dummy1.xml").read_a_customer_section()

Using this I can be able to get the text of the particular tag as expected.

But now I need to get the parent tag attibutes based on the text.

For example, If I give type "mpset" as input, I should be able to get the "account" attributes, Also I need to find the "customerdetails" attributes.

Someone help me with the same.

Hope this is clear, Else let me know I will try to make it more clear.

Upvotes: 1

Views: 471

Answers (1)

宏杰李
宏杰李

Reputation: 12158

In [3]: tree.xpath('//account[.//type="mpset"]/@id')
Out[3]: ['910']

OR:

In [4]: tree.xpath('//*[.//type="mpset"]/@id')
Out[4]: ['80', '910'] # this will return all the id attribute.

// descendant or self of root node.

. current node

.// descendant or self of current node.

.//type="mpset" current node's descendent tag type's string value is mpset

@id get id attribute

* is wildcard, match any tag

Upvotes: 2

Related Questions