我刚刚开始使用 XSL 转换 - 我想使用它们在我的项目中添加额外的抽象层。
我想使用转换将 Crystal 报表生成的 XML 文件转换为另一个 XML,为我的项目简化(这样将来,当文件架构发生更改时,我只需要更改我的 XSL 文件)。
所以我的输入 XML 文件如下所示:
<CrystalReport xmlns="urn:crystal-reports:schemas:report-detail"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="urn:crystal-reports:schemas:report-detail http://www.businessobjects.com/products/xml/CR2008Schema.xsd">
<Group Level="1">
<GroupHeader>
<Section SectionNumber="0">
<Field Name="Field4" FieldName="{@PartIndex}"><FormattedValue>Part Number</FormattedValue><Value>51-01672</Value></Field>
</Section>
<Section SectionNumber="1">
<Text Name="Text28"><TextValue>Part Description</TextValue>
</Text>
</Section>
<Section SectionNumber="2">
<Text Name="Text21"><TextValue>Part Description 2</TextValue>
</Text>
</Section>
<Section SectionNumber="3">
</Section>
...
这只是其中的一部分。我应该提到的是,GroupHeader
节点不会在 Group
节点内重复。
所以我做了一些早期的 XSL 定义(为了测试):
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:t="urn:crystal-reports:schemas:report-detail"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="urn:crystal-reports:schemas:report-detail http://www.businessobjects.com/products/xml/CR2008Schema.xsd">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:template match="/t:CrystalReport">
<ToolsUsage>
<xsl:value-of select="t:Group[1]/@Level"/>
</ToolsUsage>
</xsl:template>
</xsl:stylesheet>
我使用 lxml Python lib 来测试它。
正如预期的那样,这会返回以下代码:
<ToolsUsage xmlns:t="urn:crystal-reports:schemas:report-detail" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">1</ToolsUsage>
到目前为止,一切顺利(第一个组节点的级别属性等于“1”)。但我无法更进一步。
就像,我试图获取 Field
节点的内部文本的值(第一部分出现的):
<xsl:value-of select="t:Group[1]/GroupHeader/Section[1]/Field/Value"/>
但我没有得到任何东西(结果是在节点中)。我尝试获取 SectionNumber
属性,但也没有结果。我什至使用 XML 路径工具来提取确切的 XPath 查询,但看起来这些查询是正确的。我相信这是非常基本的东西,但无法找出是什么。
最佳答案
给定<CrystalReport xmlns="urn:crystal-reports:schemas:report-detail">...</CrystalReport>
,所有后代元素也都在命名空间中,因此您的路径需要在所有元素上使用前缀,例如t:Group[1]/t:GroupHeader/t:Section[1]/t:Field/t:Value
.
关于python - XSL转换,请求子节点数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23154738/