Xpath local-name()中的属性

Hyp*_*nja 7 python xml xpath python-2.7

这是我的xml文件的一小部分示例.

<w:p xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
   <w:pPr>
      <w:rPr>
         <w:highlight w:val="yellow"/>
      </w:rPr>
   </w:pPr>
   <w:bookmarkStart w:id="0" w:name="_GoBack"/>
   <w:bookmarkEnd w:id="0"/>
   <w:r w:rsidRPr="00D1434D">
      <w:rPr>
         <w:rFonts w:ascii="Times New Roman"
                   w:eastAsia="MS PGothic"
                   w:hAnsi="Times New Roman"/>
         <w:b/>
         <w:color w:val="000000"/>
         <w:sz w:val="24"/>
         <w:szCs w:val="24"/>
         <w:highlight w:val="yellow"/>
      </w:rPr>
      <w:t xml:space="preserve">Responses to </w:t>
   </w:r>
   <w:r w:rsidR="00335D4A" w:rsidRPr="00D1434D">
      <w:rPr>
         <w:rFonts w:ascii="Times New Roman"
                   w:eastAsia="MS PGothic"
                   w:hAnsi="Times New Roman"/>
         <w:b/>
         <w:color w:val="000000"/>
         <w:sz w:val="24"/>
         <w:szCs w:val="24"/>
         <w:highlight w:val="yellow"/>
         <w:lang w:eastAsia="ja-JP"/>
      </w:rPr>
      <w:t>the Reviewer</w:t>
   </w:r>
</w:p> 
Run Code Online (Sandbox Code Playgroud)

我想提取具有w:highlight特定属性value= "黄色"的标签的文本.我搜索了它,但无法提出解决方案.

以下作品一般用于突出显示:

for t in source.xpath('.//*[local-name()="highlight"]/../..//*[local-name()="t"]'):
     do something  
Run Code Online (Sandbox Code Playgroud)

我试过了 :

for t in lxml_tree.xpath('//*[local-name()="highlight"][@val="yellow"]/../..//*[local-name()="t"]'):
Run Code Online (Sandbox Code Playgroud)

这不起作用,什么都不返回..

har*_*r07 13

w:val属性在命名空间中,因此您不能只通过它来解决它@val.一种可能的解决方案是使用@*[local-name()='attribute name']表达式通过它的本地名称来处理属性,类似于您对元素所做的操作:

//*[local-name()="highlight"][@*[local-name()='val' and .='yellow']]/../..//*[local-name()="t"]
Run Code Online (Sandbox Code Playgroud)

  • @Swordy `@*` 表示任何属性,类似于 `//*` 表示任何元素。`.` 引用当前上下文,在该特定用法中,它是由 `@*` 引用的属性的值 (2认同)