带有标签特定信息的 Python XML 解析 [英] Python XML Parsing with Tag Specific Info

查看:45
本文介绍了带有标签特定信息的 Python XML 解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个结构如下的 XML 文件:

I have an XML file with a structure like the following:

<?xml version="1.0">
<title>
  <ch bk="Book1" num="1">
    <ver num="1">ver1 content</ver>
    <ver num="2">ver2 content</ver>
  </ch>
  <ch bk="Book1" num="2">
    <ver num="1">ver1 content</ver>
    <ver num="2">ver2 content</ver>
  </ch>
  <ch bk="Book2" num="1">
    <ver num="1">ver1 content</ver>
    <ver num="2">ver2 content</ver>
  </ch>
</title>

有没有办法可以在 python 中访问特定 ch num 和 book 的单个 ver 内容?(例如访问ver num=2 of ch num=2 of bk=Book1)我查看了一些解析 XML 的 xml 模块类,但是它们通过 tagName 进行,我看不到在哪里可以输入信息,例如 num、bk 和 ch.非常感谢!

Is there a way I can access individual ver content for a specific ch num and book in python? (for example, access ver num=2 of ch num=2 of bk=Book1) I've looked at a few xml module classes that parse XML, however they go by tagName, and I don't see where I can input info such as num, bk, and ch. Thanks a lot!

推荐答案

您可以访问具有良好 表达式:

You can access an element with a fine xpath expression :

// 代表相对 &递归搜索

// stands for relative & recursive search

'//ch[@num="1"][@bk="Book1"]/ver[@num="1"]'
#  ^      ^        ^           ^      ^
# ch node |        |           |      |
#  + attributes num = 1        |      |
#  + AND Book attribute = 1    |      |
#                           ver node  |
#                           + num attribut = 1

蟒蛇代码:

from lxml import etree
fp = open("/tmp/xml.xml")
tree = etree.parse(fp)
print(tree.xpath('//ch[@num="1"][@bk="Book1"]/ver[@num="1"]/text()')[0])

这篇关于带有标签特定信息的 Python XML 解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆