如何通过xpath获取最新日期?

问题描述:

我旁边的xml:如何通过xpath获取最新日期?

<Content> 
<article title="I Compute, Therefore I am" id="a1"> 
     <authors> 
      <author>Philbert von Cookie</author> 
      <author>Alice Brockman</author> 
      <author>Pedro Smith</author> 
     </authors> 
     <journal> 
      <name>Journal of Computational Metaphysics</name> 
      <volume>3</volume> 
      <issue>7</issue> 
      <published>04/11/2006</published> 
      <pages start="42" end="49"/> 
     </journal> 
</article> 
... 
</Content> 

有很多根元素中类似的文章节点 - >内容

我已经解析我的XML到Python代码,并希望得到最大的日期值。这里是我的蟒蛇代码:

try: 
    import xml.etree.cElementTree as ET 
except ImportError: 
    import xml.etree.ElementTree as ET 

tree = ET.ElementTree(file='data.xml') 
root = tree.getroot() 
root.tag, root.attrib 

我想使用iterfind(),但它不工作到目前为止。

for elem in tree.iterfind('(/*/*/journal/published/value[not(text() < preceding-sibling::value/text()) and not(text() < following-sibling::value/text())])[1]'): 
print (elem.text) 

你能帮我解答我该如何设置我的XPATH for iterfind()或者可能有其他方法可以做到这一点? 谢谢。

xml.etree.ElementTree只提供limited xpath support

一种替代选择是将所有日期解析成一个列表,并获得最大的价值:

from datetime import datetime 

dates = [published.text for published in root.iterfind('.//article/journal/published')] 
print max(dates, key=lambda x: datetime.strptime(x, '%d/%m/%Y')) 

注意的是,为了找到在这种情况下最大值,你应该比较datetime值,而不是字符串(这是key功能帮助的地方)。


另外,如果你想获得相应的最大日journal记录,你可以构造一个字典映射“日期 - >日志”,然后获得相应的日志记录:

from datetime import datetime 
import operator 

try: 
    import xml.etree.cElementTree as ET 
except ImportError: 
    import xml.etree.ElementTree as ET 

tree = ET.ElementTree(file='data.xml') 
root = tree.getroot() 

mapping = {datetime.strptime(journal.findtext('published'), '%d/%m/%Y'): journal 
      for journal in root.iterfind('.//article/journal')} 

journal_latest = max(mapping.iteritems(), key=operator.itemgetter(0))[1] 
print journal_latest.findtext('name') 
+0

我无法运行代码的最后部分。蟒蛇说语法错误: 回溯(最近通话最后一个): 文件 “find.py”,13号线,在 在root.iterfind杂志( './/文/日志')} 文件“找到.py“第13行 for root.iterfine('.// article/journal')} 文件”C:\ Python34 \ lib \ _strptime.py“,第500行,位于_strptime_datetime tt,分数= _strptime(data_string,格式) 文件“C:\ Python34 \ lib \ _strptime.py”,行337,位于_strptime (data_string,format)) ValueError:时间数据'05/25/2002'不匹配格式'%d /%m /%Y' – 2014-10-18 02:15:20

+0

@DonKorleone格式不是我所期待的,换掉月份和da y:'%m /%d /%Y'而不是'%d /%m /%Y'。 – alecxe 2014-10-18 02:17:08

+0

以及如何使用journal.findtext('published')?什么是日志?如果这是节点的名称,它之前定义的位置?对不起,可能是这个简单的问题,但我是新的python。所以我将不胜感激,如果你可以一步一步解释 – 2014-10-18 02:25:45