【问题标题】:Filtering xml file to remove lines with certain text in them?过滤xml文件以删除其中包含某些文本的行?
【发布时间】:2011-09-27 18:21:02
【问题描述】:

例如,假设我有:

<div class="info"><p><b>Orange</b>, <b>One</b>, ...
<div class="info"><p><b>Blue</b>, <b>Two</b>, ...
<div class="info"><p><b>Red</b>, <b>Three</b>, ...
<div class="info"><p><b>Yellow</b>, <b>Four</b>, ...

我想从列表中删除所有包含单词的行,所以我只会在符合我标准的行上使用 xpath。例如,我可以将列表用作['Orange', 'Red'] 来标记不需要的行,因此在上面的示例中,我只想使用第 2 行和第 4 行进行进一步处理。

我该怎么做?

【问题讨论】:

  • 好问题,+1。请参阅我的答案以获得完整、简短且简单的单行 XPath 表达式解决方案。

标签: python html xml xpath lxml


【解决方案1】:

使用

//div
  [not(p/b[contains('|Orange|Red|', 
                    concat('|', ., '|')
                   )
          ]
       )
  ]

这会选择 XML 文档中的任何 div 元素,这样它就没有 p 子元素,其 b 子元素的字符串值是管道分隔的字符串列表中用作过滤器的字符串之一。

这种方法通过将新过滤器值添加到管道分隔列表来实现可扩展性,而无需更改 XPath 表达式中的任何其他内容。

注意:当静态已知 XML 文档的结构时,请始终避免使用 // XPath 伪运算符,因为它会导致显着的低效率(减速)。

【讨论】:

    【解决方案2】:
    import lxml.html as lh
    
    # http://lxml.de/xpathxslt.html
    # http://exslt.org/regexp/functions/match/index.html
    content='''\
    <table>
    <div class="info"><p><b>Orange</b>, <b>One</b></p></div>
    <div class="info"><p><b>Blue</b>, <b>Two</b></p></div>
    <div class="info"><p><b>Red</b>, <b>Three</b></p></div>
    <div class="info"><p><b>Yellow</b>, <b>Four</b></p></div>
    </table>
    '''
    NS = 'http://exslt.org/regular-expressions'
    tree = lh.fromstring(content)
    exclude=['Orange','Red']
    for elt in tree.xpath(
        "//div[not(re:test(p/b[1]/text(), '{0}'))]".format('|'.join(exclude)),
        namespaces={'re': NS}):
        print(lh.tostring(elt))
        print('-'*80)
    

    产量

    <div class="info"><p><b>Blue</b>, <b>Two</b></p></div>
    
    --------------------------------------------------------------------------------
    <div class="info"><p><b>Yellow</b>, <b>Four</b></p></div>
    
    --------------------------------------------------------------------------------
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-23
      • 1970-01-01
      • 1970-01-01
      • 2018-11-16
      • 2022-01-17
      • 2013-11-04
      • 2021-06-24
      • 2014-09-19
      相关资源
      最近更新 更多