将xml中的节点值与Python中的String进行比较

时间:2014-03-03 12:48:05

标签: python xml comparison

经过大量搜索并尝试了很多次,我无法将xml中的节点与python脚本中从User输入的字符串进行比较。 我希望这是由于类型不匹配,因为我从unicode格式的XML中获取价值, 请建议ASAP成功比较两个字符串的方式。 在此先感谢。

我的Python脚本:

from  xml.dom.minidom import *
def codin(code):
        document = 'fourth.xml'
        xmldoc = parse(document)
        itemlist = xmldoc.getElementsByTagName('item')
        kool =  itemlist[0].attributes['name'].value
        print kool
        if code ==  kool:
                print type(kool)
                print type(code)
                print "found"
        else:
                print "not found"


        for s in itemlist :
                if code in s.attributes['name'].value:
                        print "Country code matched "
                        country = s.firstChild.nodeValue
                        print country
                        print type(country)
                else:
                        print "not found"

codin('001')

XML数据:

<data>
    <items>
        <item name="001">India</item>
        <item name="002">China</item>
        <item name="003">Spain</item>
        <item name="004">Pakistan</item>
    </items>
</data>

2 个答案:

答案 0 :(得分:1)

目前尚不清楚你的期望。以下代码从xml文件中读取值并将其存储为字典,以便您可以在字典中进行比较。

from  xml.dom.minidom import *
def codin(code):
    document = 'fourth.xml'
    xmldoc = parse(document)
    items = xmldoc.getElementsByTagName('items')
    kool = ""
    countryKool = {}
    for n in items:
        rv = getChild(n,'item')
        for v in rv:
            country = v.childNodes[0].nodeValue
            attr = v.getAttributeNode('name')
            if attr:
                kool = attr.nodeValue.strip()
                print "One of item is " , country, " and attribute is ",kool
                countryKool[kool] = country

    if code in countryKool:
        print "found"
    else:
        print "not found"

    print "Mapping of Country and kool ", countryKool #contains mapping for country and kool


def getChild(n,v):
    for child in n.childNodes:
        if child.localName==v:
            yield child

codin('001')

输出:

One of item is  India  and attribute is  001
One of item is  China  and attribute is  002
One of item is  Spain  and attribute is  003
One of item is  Pakistan  and attribute is  004
found
Mapping of Country and kool  {u'003': u'Spain', u'002': u'China', u'001': u'India', u'004': u'Pakistan'}

答案 1 :(得分:0)

我解决了这个问题,我只需要删除字符串并解析它:)