本文介绍了子树的Python XML搜索值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在正在进行修改,所以如果我想搜索999并打印整个blub:Log

I am now working on a modification so what do I need to do if I want to search for 999 and print the whole blub:Log

通过使用,我会找到999findLogIter = tree.find("999")但是我如何告诉他打印整个内容?

I would find 999 by usingfindLogIter = tree.find("999") but how do I tell him to print the whole thing?

<blub:LogEvents>
 <blub:Log>
  <blub:LogTime>09/03/2017 01:02:16.3216</blub:LogTime>
  <blub:LogIter>999</blub:LogIter>
  <blub:PlugInName>blub:System</blub:PlugInName>
  <blub:EventNumber>100</blub:EventNumber>
  <blub:EventName>I processed something</blub:EventName>
  <blub:EventClass>Process</blub:EventClass>
  <blub:LogMessage><![test message]]></blub:LogMessage>
 </blub:Log>
</blub:LogEvents>

输出应如下所示:

09/03/2017 01:02:16.3216,999,blub:System,100,I processed something,Process

对于LogEvents中的每个日志,

推荐答案

查找LogIter,如果该子元素具有"999"文本,则对该日志调用getItemStr().如果不存在"999"子元素,则将附加无"列表.因此,请使用无"过滤结果列表.

for every Log in LogEvents, find for LogIter and if that subelement has "999" text then call getItemStr() for that Log. If "999" subelement is not present, a None list will be appended. Hence, filter the result list with None.

from xml.etree import ElementTree
tree = ElementTree.parse('sample.xml')
root = tree.getroot()

def getItemStr(item):
    return ','.join([sub_item.text for sub_item in item])

print filter(None,[[getItemStr(item) for child in item.findall('blub:LogIter',{"blub":"Uri"}) if child.text=="999"] for item in root ])

如果最后一行抛出错误,您甚至可以使用

If that last line throws error, You an even use

print filter(None,[[getItemStr(item) for child in item.findall('blub:LogIter') if child.text=="999"] for item in root ])

在python 2.6和更早版本中,您必须像

print filter(None,[[getItemStr(item) for child in item.findall('{Uri}LogIter') if child.text=="999"] for item in root ])

输出:

[['09/03/2017 01:02:16.3216,999,blub:System,100,I processed something,Process,hello']]

在您的xml中添加一个像xmlns:blub="Uri"这样的名称空间!

Add a namespace like xmlns:blub="Uri" to your xml!

<blub:LogEvents xmlns:blub="Uri">
 <blub:Log>
  <blub:LogTime>09/03/2017 01:02:16.3216</blub:LogTime>
  <blub:LogIter>999</blub:LogIter>
  <blub:PlugInName>blub:System</blub:PlugInName>
  <blub:EventNumber>100</blub:EventNumber>
  <blub:EventName>I processed something</blub:EventName>
  <blub:EventClass>Process</blub:EventClass>
  <blub:LogMessage>hello</blub:LogMessage>
 </blub:Log>
<blub:Log>
  <blub:LogTime>09/03/2011 01:02:16.3216</blub:LogTime>
  <blub:LogIter>1000</blub:LogIter>
  <blub:PlugInName>blub:System</blub:PlugInName>
  <blub:EventNumber>100</blub:EventNumber>
  <blub:EventName>I processed something</blub:EventName>
  <blub:EventClass>Process</blub:EventClass>
  <blub:LogMessage>hi</blub:LogMessage>
 </blub:Log>
</blub:LogEvents>

希望有帮助!

这篇关于子树的Python XML搜索值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 18:26