0

我有一个如下的xml文件,现在我想使用XSLT对其进行转换,保留所有元素和属性,但是如果它发生在值以“SQL:”开头的属性上,则执行sql并替换具有已解析 SQL 的属性值(它涉及http://msdn.microsoft.com/en-us/library/533texsx(VS.90).aspx。现在我遇到了问题:如何检查当前节点类型是属性,以及如何替换属性值,我基于Visual Studio的默认模板如下:

示例 xml 文件(实际上有很多元素):

<DM>
  <DV  id="SQL:Select something from db">
    <Sample aid="SQL:Select something from db">

    </Sample>
  </DV>
  <DV  id="SQL:Select something from db">
    <Sample aid="SQL:Select something from db">
    </Sample>
  </DV>
</DM>

默认xslt:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl"
               xmlns:ms="urn:schemas-microsoft-com:xslt" >
  <xsl:output method="xml" indent="yes"/>

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

2 回答 2

2

这个样式表:

<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="@*[starts-with(translate(substring(.,1,4),'sql','SQL'),'SQL:')]">
        <xsl:attribute name="{name()}">
            <xsl:value-of select="'From SQL!'"/>
        </xsl:attribute>
    </xsl:template>
</xsl:stylesheet>

结果:

<DM>
    <DV id="From SQL!">
        <Sample aid="From SQL!"></Sample>
    </DV>
    <DV id="From SQL!">
        <Sample aid="From SQL!"></Sample>
    </DV>
</DM>

注意:不需要打破“身份转换”。使用 .将属性添加到结果树xsl:attribute

于 2010-07-20T13:28:31.300 回答
1

好吧,您正在使用一个模板来匹配节点和属性。使用两个单独的模板会更容易区分它们:

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

<!-- Another template for attributes -->
<xsl:template match="@*">
  <!-- Special case for SQL attributes goes here -->
</xsl:template>

要确定字符串是否以特定子字符串开头,您需要使用starts-with()函数。你可以像这样使用它:

<xsl:if test="starts-with(.,'SQL:')">
  <!-- The current node starts with "SQL:" -->
</xsl:if>
于 2010-07-20T12:53:35.957 回答