【发布时间】:2017-10-23 17:25:50
【问题描述】:
使用以下 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 调用上相关键的值。提前致谢。
【问题讨论】:
标签: python xml xpath ironpython