简体   繁体   中英

Filtering xml: XSLT with lxml in python

fTrying to filter the xml input with XSLT, I have problem running the following code. I think there is a problem with the defined XSLT..I would like to define a rule in XSLT to discard 'Foo' element in the input xml. This is how my code looks like:

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()

What you are missing is the correct template-match .

Modified code:

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()

This outputs:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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