简体   繁体   English

如何在 xpath 中插入变量 - Python

[英]How to insert a variable in xpath - Python

I need to parse the XML contact details (phone and email) only when name = 'XX Davis'仅当 name = 'XX Davis' 时,我才需要解析 XML联系方式(电话和电子邮件)

<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="jXX@city.com"/>
                </CONTACT_DETAIL>
                <CONTACT_DETAIL _Name="Davis">
                    <CONTACT_POINT _Type="Phone" _Value="123657"/>
                    <CONTACT_POINT _Type="Email" _Value="yyy@city.com"/>
                </CONTACT_DETAIL>
            </REQUESTING_PARTY>
        </REQUEST_GROUP>]]>
</PAYLOAD>
</B2B_DATA>

I have contact detail name parsed else where and stored in varcontactName我在其他地方解析了联系人详细信息名称并存储在 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.请帮忙。

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: Output:

['123657', 'yyy@city.com']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM