在SelectSingleNode

时间:2017-05-23 16:22:16

标签: python xml xpath ironpython

使用以下XML数据我想获得我通过python代码调用的相关键的值。我想在不使用任何第三方库的情况下完成此任务。

<Userinfo>
  <UserData>
     <item key="DateOfBirth" value="19851103" />
     <item key="FirstName" value="John" />
     <item key="LastName" value="Dicaprio" />
     <item key="Gender" value="M" />
     <item key="Email" value="john@abc.com" />
     <item key="ContactNo" value="235625341" />
  </UserData>
</Userinfo>

从上面的xml代码中我想从我在下面的python代码中调用的键中提取值。

def ExtractXml(args):
url = '....'
wc = System.Net.WebClient()
xml = wc.DownloadString(url)
doc = System.Xml.XmlDocument()
doc.LoadXml(xml)
root = doc.DocumentElement
nsmgr = System.Xml.XmlNamespaceManager(doc.NameTable)
#nsmgr.AddNamespace('ns','http://schemas.microsoft.com/developer/msbuild/2003')
node = root.SelectNodes('/Userinfo/UserData',nsmgr)
tcount=root.SelectNodes('/Userinfo/UserData').Count

if not node: 
    ServiceDesk.Log.PrintError('No condition node')
    return

r=[]
t={}

counts=0
for itemNode in node:
    counts += 1
    fullname = xstr(itemNode.SelectSingleNode("/item[@key='FirstName']/@value",nsmgr))
    empname = xstr(itemNode.SelectSingleNode("/item[@key='LastName']/@value",nsmgr))
    cardcountry = xstr(itemNode.SelectSingleNode("/item[@key='Email']/@value",nsmgr))
    #birthdate = ServiceDesk.Common.ParseDateTime(itemNode.SelectSingleNode("item[@key='DateOfBirth']"))

    t = {'counter':counts,'FirstName':fullname,'LastName':empname,'Email':cardcountry,'__rowid__':counter,'__totalcount__':tcount}
    r.append(t)
return r

使用以下代码,它不会在SelectSingleNode调用上检索相关键的值。提前谢谢。

2 个答案:

答案 0 :(得分:0)

我对IronPython不太确定,但Python的核心库包含一些其他独立于平台的XML解析器...这是一个使用xml.etree.ElementTree的示例。

import datetime
import xml.etree.ElementTree as ET

xml = '''<Userinfo>
    <UserData>
        <item key="DateOfBirth" value="19851103" />
        <item key="FirstName" value="John" />
        <item key="LastName" value="Dicaprio" />
        <item key="Gender" value="M" />
        <item key="Email" value="john@abc.com" />
        <item key="ContactNo" value="235625341" />
    </UserData>
</Userinfo>'''

root = ET.fromstring(xml)
fname = root.findall(".//item[@key='FirstName']")[0].get('value')
dob = datetime.datetime.strptime(
        root.findall(".//item[@key='DateOfBirth']")[0].get('value'),
        '%Y%m%d')

答案 1 :(得分:0)

目前for循环中的XPath表达式都是相对于文档节点的,因为它始于/。要使其相对于上下文元素(在本例中为itemNode引用),您可以添加前面的.或完全删除/

for itemNode in node:
    counts += 1
    # here are some ways to make your XPath heeds the context element `itemNode`
    fullname = xstr(itemNode.SelectSingleNode("./item[@key='FirstName']/@value",nsmgr))
    empname = xstr(itemNode.SelectSingleNode("item[@key='LastName']/@value",nsmgr))
    cardcountry = xstr(itemNode.SelectSingleNode("self::*/item[@key='Email']/@value",nsmgr))