我有一些XML正在试图解析。示例:
<TVAMain>
<ProgramDescription>
<ProgramLocationTable>
<Schedule value1="1234">
<ScheduleEvent>
<Program value2="1234567890" />
</ScheduleEvent>
<ScheduleEvent>
<Program value2="1234567891" />
</ScheduleEvent>
</Schedule>
<Schedule value1="5678">
<ScheduleEvent>
<Program value2="1234567892" />
</ScheduleEvent>
<ScheduleEvent>
<Program value2="1234567893" />
</ScheduleEvent>
</Schedule>
</ProgramLocationTable>
</ProgramDescription>
</TVAMain>
我试图检索value1的所有条目和value2的所有条目,并将它们作为value1 | value2输出到一个文件中。我可以成功地将值1或值2写入文件,但不能同时获取它们!在
这是我目前为止的代码(我暂时放弃了编写步骤,只想让它先打印出两位数据):
^{pr2}$此代码将成功打印所有“value1”值,但不打印value2。在
我试过以下方法: -在第二个for循环中使用“info2” -使用第二个xpath,为value1输入已知值
有人能给我指出正确的方向吗?在
使用您发布的XML,您可以使用一个XPath找到所有值:
印刷品
^{pr2}$此XPath假定始终有一个
value1
属性,后跟两个value2
属性。如果你不想依赖这个假设,那么你可以这样循环:在您的代码中:
由于
"value1"
是一个文本字符串,因此无效。您需要将其替换为变量value1
:虽然这样做是可行的,但是指定
value1
可能比您需要的更具体。或者,如果两个Schedule
元素具有相同的value1
属性,则可能不够具体。相反,您可以通过调用schedule.xpath
找到子元素Program
元素:而不是从树的顶部开始使用
tree.xpath
。在另一种使用
lxml
的方法是:这将打印出:
^{pr2}$相关问题 更多 >
编程相关推荐