首页 > 解决方案 > Python,如何获取 xsl 样式表的参数?

问题描述

我想获取xsl用于将文件转换为xml文件的csv文件的参数。我特别想得到这条线:

<xsl:param name="sep" select="','"/>

我试过的:

 with open(file, "r") as file:
    content = file.readlines()
    regex = re.compile(r"""<xsl:param +name *= *"[0-9A-Za-z]+" +select *= *"\\'.\\'"/>""")
    for line in content:
        print(line)
        match = regex.match(line)
        if match:
            pass
            # do something

我尝试了不同的正则表达式,但没有任何效果。我正在使用 python 3.6 并lxml对其进行转换。

编辑xsl 文件:

<?xml version="1.0" encoding="UTF-8"?>

<xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:output method="text"/>
  <xsl:strip-space elements="*"/>
  <xsl:param name="sep" select="','"/>
  <xsl:param name="test" select="','"/>
  <xsl:param name="test2" select="','"/>

  <xsl:template match="/">title,artist,country,company,price,year
<xsl:for-each select="catalog/cd">
<xsl:value-of select="concat('&quot;', title, '&quot;', $sep, '&quot;', artist, '&quot;', $sep, '&quot;',
country, '&quot;', $sep, '&quot;', company, '&quot;', $sep, price, $sep, year, '&#10;')"/>
</xsl:for-each>
  </xsl:template>

</xsl:stylesheet>

标签: pythonregexxslt

解决方案


您可以使用xml解析器来完成。像这样:

假设您的文件是test.xsl. 然后你可以这样做:

import xml.etree.ElementTree as ET
tree = ET.parse('test.xsl')
root = tree.getroot()
match = [c.attrib for c in root if 'param' in c.tag]

然后match看起来像这样:

>>> print(match)
[{'name': 'sep', 'select': "','"}, {'name': 'test', 'select': "','"}, {'name': 'test2', 'select': "','"}]

我假设您不需要整行,只需要<>标签之间的属性。拥有这些属性将允许您创建所需的csv文件。


推荐阅读