Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/335.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何获取特定的XML标记值?_Python_Xml_Python 2.7_Xml Parsing - Fatal编程技术网

Python 如何获取特定的XML标记值?

Python 如何获取特定的XML标记值?,python,xml,python-2.7,xml-parsing,Python,Xml,Python 2.7,Xml Parsing,有没有办法获取XML标记的特定值 <Country Rank="0"> <Name>xyz</Name> <Place>abcd</IntValue> </Country> <Country Rank="1"> <Name>xyz1</Name> <Place>abcd1</IntValue> </Country> <Count

有没有办法获取XML标记的特定值

<Country Rank="0">
  <Name>xyz</Name>
  <Place>abcd</IntValue>
 </Country>
<Country Rank="1">
  <Name>xyz1</Name>
  <Place>abcd1</IntValue>
 </Country>
<Country Rank="2">
  <Name>xyz2</Name>
  <Place>abcd2</IntValue>
 </Country>
使用:

其中
e
是树或元素根。Xpath
“//Country[@rank='1']”
中的秩值可用于更改所需的秩,因此您可以生成如下函数:

def get_places_by_rank(e, rank):
    xpath = ".//Country[@Rank='{}']".format(rank)
    return [place.text for country in e.findall(xpath) for place in country.iter("Place")]
然后像这样使用它:

>>> e=ET.fromstring("""
... <Countries>
...     <Country Rank="0">
...         <Name>xyz</Name>
...         <Place>abcd</Place>
...     </Country>
...     <Country Rank="1">
...         <Name>xyz1</Name>
...         <Place>abcd1</Place>
...     </Country>
...     <Country Rank="2">
...         <Name>xyz2</Name>
...         <Place>abcd2</Place>
...     </Country>
...  </Countries>""")
>>>
>>> get_places_by_rank(e, 1)
['abcd1']
>>> get_places_by_rank(e, 2)
['abcd2']
>>> get_places_by_rank(e, 3)
[]
>>> get_places_by_rank(e, 0)
['abcd']
>e=ET.fromstring(“”)
... 
...     
…xyz
…abcd
...     
...     
…xyz1
…abcd1
...     
...     
…xyz2
…abcd2
...     
...  """)
>>>
>>>按排名(e,1)获得排名
['abcd1']
>>>按排名(e,2)获得排名
['abcd2']
>>>按排名(e,3)获得排名
[]
>>>按排名(e,0)获取位置
['abcd']

我已经删除了你问题中明确离题的部分。其余的看起来很像是对代码的请求——这不是一个代码编写服务。请展示您试图实现这一点的一个例子,并准确描述其中的问题。@jonrsharpe:用最少的例子编辑。请帮助我。”…并准确描述它的问题”。那么,在这里,我如何获取像abcd2、abcd1等值?
def get_places_by_rank(e, rank):
    xpath = ".//Country[@Rank='{}']".format(rank)
    return [place.text for country in e.findall(xpath) for place in country.iter("Place")]
>>> e=ET.fromstring("""
... <Countries>
...     <Country Rank="0">
...         <Name>xyz</Name>
...         <Place>abcd</Place>
...     </Country>
...     <Country Rank="1">
...         <Name>xyz1</Name>
...         <Place>abcd1</Place>
...     </Country>
...     <Country Rank="2">
...         <Name>xyz2</Name>
...         <Place>abcd2</Place>
...     </Country>
...  </Countries>""")
>>>
>>> get_places_by_rank(e, 1)
['abcd1']
>>> get_places_by_rank(e, 2)
['abcd2']
>>> get_places_by_rank(e, 3)
[]
>>> get_places_by_rank(e, 0)
['abcd']