Python 属性解析对于 xml :id 返回 None

标签 python python-3.x xml-parsing attributes elementtree

我正在尝试使用以下代码从 tei 文件中提取一些信息:

tree = ET.parse(path)
root = tree.getroot()
body = root.find("{http://www.tei-c.org/ns/1.0}text/{http://www.tei-c.org/ns/1.0}body")  
for s in body.iter("{http://www.tei-c.org/ns/1.0}s"):
    for w in s.iter("{http://www.tei-c.org/ns/1.0}w"):
        wordpart = w.find("{http://www.tei-c.org/ns/1.0}seg")
        word = ''.join(wordpart.itertext())
        type = w.get('type')
        xml = w.get('xml:id') 
        print(type)             
        print(xml)

type 的输出是正确的,它打印例如“名词”。但对于 xml:id 我只能得到 None。这是我需要解析的 xml 文件的摘录:

<w type="noun" xml:id="w.4940"><seg type="orth">sloterheighe</seg>...

最佳答案

要获取 xml:id 属性的值,您需要像这样指定命名空间 URI(有关更多详细信息,请参阅 this SO post):

xml = w.attrib['{http://www.w3.org/XML/1998/namespace}id']

xml = w.get('{http://www.w3.org/XML/1998/namespace}id')

另外,请注意 type 是 Python 中的内置方法,因此请避免将其用作变量名称。

关于Python 属性解析对于 xml :id 返回 None,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55918959/

相关文章:

python - bson.errors.InvalidDocument : key '$numberDecimal' must not start with '$' when using json

Node.js - Xml 解析

java - 如何生成包含已解析实体的 XML 文档的*精确*副本

xml-parsing - 使用 JAXB 对 XML 进行部分解码以跳过一些 xmlElement

python - 递归计算二叉树中的节点

python - 如何将第 3 方 Python 库导入 Bluemix?

Python 日志记录 : unicode symbols is unicode-escaped

python - 在 Pandas 中同时替换空白和空字段

python-3.x - 使用 gitpython,如何 check out 某个 Git 提交 ID?

python - 如何在子类中调用父类?