Home > Blockchain >  How to insert a variable in xpath - Python
How to insert a variable in xpath - Python

Time:07-30

I need to parse the XML contact details (phone and email) only when name = 'XX Davis'

<B2B_DATA>
   <B2B_METADATA>
       <EventId>122157660</EventId>
       <MessageType>Request</MessageType>
   </B2B_METADATA>
<PAYLOAD>
    <![CDATA[<?xml version="1.0"?>
        <REQUEST_GROUP MISMOVersionID="1.1.1">
            <REQUESTING_PARTY _Name="CityBank" _StreetAddress="801 Main St" _City="rockwall" _State="MD" _PostalCode="11311" _Identifier="416">
                <CONTACT_DETAIL _Name="John">
                    <CONTACT_POINT _Type="Phone" _Value="1236573348"/>
                    <CONTACT_POINT _Type="Email" _Value="[email protected]"/>
                </CONTACT_DETAIL>
                <CONTACT_DETAIL _Name="Davis">
                    <CONTACT_POINT _Type="Phone" _Value="123657"/>
                    <CONTACT_POINT _Type="Email" _Value="[email protected]"/>
                </CONTACT_DETAIL>
            </REQUESTING_PARTY>
        </REQUEST_GROUP>]]>
</PAYLOAD>
</B2B_DATA>

I have contact detail name parsed else where and stored in varcontactName

I have tried this

varcontactName = doc.xpath('//REQUESTING_PARTY/CONTACT_DETAIL/@_Name"][0]

doc.xpath('//REQUESTING_PARTY/CONTACT_DETAIL[@_Name='   varcontactName 
   ']/CONTACT_POINT[@_Type="Phone"]/@_Value')[0]

its taking it as 

doc.xpath('//REQUESTING_PARTY/CONTACT_DETAIL[@_Name=John]/CONTACT_POINT[@_Type="Phone"]/@_Value')[0]


i need it as 
doc.xpath('//REQUESTING_PARTY/CONTACT_DETAIL[@_Name="John"]/CONTACT_POINT[@_Type="Phone"]/@_Value')[0]

i am unable get the string with quotes.

Please help.

CodePudding user response:

If I understand you correctly, you are looking for something like this:

from lxml import etree
b2b = """[your xml above]"""
doc= etree.XML(b2b)

varcontactName = []
#extract the cdata from the outer xml:
cd = doc.xpath('//PAYLOAD//text()')[0].strip()
#parse the cdata into a new document:
doc2 = etree.XML(cd)

#search for your target attributes in elements where the _Name attribute
#has a value of "Davis":
targets = ["Phone", "Email"]

for entry in doc2.xpath('//REQUESTING_PARTY//CONTACT_DETAIL[@_Name="Davis"]'):
    for target in targets:
        varcontactName.append(entry.xpath(f'./CONTACT_POINT[@_Type="{target}"]/@_Value')[0])
varcontactName

Output:

['123657', '[email protected]']
  • Related