繁体   English   中英

过滤xml:Python中带有lxml的XSLT

[英]Filtering xml: XSLT with lxml in python

f尝试使用XSLT过滤xml输入时,我在运行以下代码时遇到问题。 我认为定义的XSLT存在问题。我想在XSLT中定义一个规则,以丢弃输入xml中的“ Foo”元素。 这是我的代码的样子:

from lxml import etree
from io import StringIO

def testFilter():

  xslt_root = etree.XML('''\
  <xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 

  <xsl:template match="Foo"/>

  </xsl:stylesheet>
  ''')

  transform = etree.XSLT(xslt_root)

  f = StringIO(unicode('<?xml version="1.0"?><ComponentData><DataSet name="one">  <Foo fooValue="2014"/></DataSet><DataSet   name="two"><Foo fooValue="2015"/></DataSet></ComponentData>
  ')) 

  doc = etree.parse(f)
  result_tree = transform(doc)

  print(str(result_tree))  

if __name__=='__main__':
  testFilter()

您缺少的是正确的template-match

修改后的代码:

from lxml import etree
from io import StringIO

def testFilter():
  xslt_root = etree.XML('''\
  <xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 

  <xsl:template match="node() | @*">
    <xsl:copy>
        <xsl:apply-templates select="node() | @*"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="TimeStamp"/>

  </xsl:stylesheet>
  ''')

  transform = etree.XSLT(xslt_root)

  f = StringIO(unicode('<?xml version="1.0"?><ComponentData><DataSet name="one">  <TimeStamp timeStampValue="2014"/></DataSet><DataSet name="two"><TimeStamp timeStampValue="2015"/></DataSet></ComponentData>')) 
  doc = etree.parse(f)
  result_tree = transform(doc)

  print(str(result_tree))  

if __name__=='__main__':
  testFilter()

输出:

<?xml version="1.0"?>
<ComponentData><DataSet name="one">  </DataSet><DataSet name="two"/></ComponentData>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM