python - 提取属性值,Lxml

标签 python xml python-2.7 xpath lxml

我有以下 Xml 文件:

'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n<w:document xmlns:wpc="http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:wp14="http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing" xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:w10="urn:schemas-microsoft-com:office:word" xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml" xmlns:wpg="http://schemas.microsoft.com/office/word/2010/wordprocessingGroup" xmlns:wpi="http://schemas.microsoft.com/office/word/2010/wordprocessingInk" xmlns:wne="http://schemas.microsoft.com/office/word/2006/wordml" xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape" mc:Ignorable="w14 wp14"><w:body><w:p w:rsidR="00706A37" w:rsidRPr="004A1CE5" w:rsidRDefault="004A1CE5"><w:pPr><w:pStyle w:val="Heading1"/><w:numPr><w:ilvl w:val="12"/><w:numId w:val="0"/></w:numPr><w:rPr><w:sz w:val="28"/><w:szCs w:val="28"/></w:rPr></w:pPr><w:commentRangeStart w:id="0"/><w:r w:rsidRPr="004A1CE5"><w:rPr><w:sz w:val="28"/><w:szCs w:val="28"/></w:rPr><w:t>H</w:t></w:r><w:commentRangeEnd w:id="0"/><w:r w:rsidR="00A23794"><w:rPr><w:rStyle w:val="CommentReference"/> 

我需要提取 id 的值在<w:commentRangeStart>内标签 。我查看了很多关于 SO 的问题,发现了以下类型:

我尝试过: (使用 commentRangeStart 标签迭代每个 p,并检索 attrib。这没有返回任何内容。

for p in lxml_tree.xpath('.//w:p/commentRangeStart',namespaces = {'w':w}):
    print p.attrib

我尝试了 'commentRangeStart[@id]' 的各种组合和commentRangeStart/@id但没有一个起作用。我提到了很多问题,其中之一是 here .
我更喜欢一种遍历每个 p 然后搜索评论标签的方式。喜欢:

for p in lxml_tree.xpath('.//w:p',namespaces = {'w':w}):  
    p.xpath(./w:commentRangeStart/...)

等等..

我的表情怎么了??

最佳答案

您需要限定命名空间:

for p in root.xpath('.//w:p/w:commentRangeStart', namespaces={'w':w}):
    print p.attrib

输出:

{'{http://schemas.openxmlformats.org/wordprocessingml/2006/main}id': '0'}
<小时/>

替代方案:

for id_ in root.xpath('.//w:p/w:commentRangeStart/@w:id', namespaces={'w': w}):
    print id_

输出:

0

关于python - 提取属性值,Lxml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26237401/

相关文章:

python 发布请求不适用于 Minio 服务器导入

python - 如何同时处理在线程之间传递数据(3 个 while True 循环)?

python - 将 Mixer 与 Flask-SQLAlchemy 结合使用

xml - 如何在 WSO2 Integration 上将自闭标签 xml 转换为空标签 xml

python - 在其他 Linux 计算机上运行已编译的 Linux 可执行文件

python - 行中列表的元素

python - 使用 lxml 将 xml 转换为 Python 数据结构

java - 在android中自定义图片库

csv - Pandas read_csv 和 UTF-16

python - 在具有多个值的键的字典中查找公共(public)值