如何使用C#函数将XML转换为XSLT转换

问题描述:

我有如下动态生成的XML,它在运行时填充节点值。如何使用C#函数将XML转换为XSLT转换

<?xml version="1.0" encoding="utf-8" ?> 
<master> 
    <child> 
    <category1>Category1_A</category1> 
    <category2>Category2_B </category2> 
    </child> 
</master> 

我有我的web.config类别代码和配置的关键如下

<add key="Code" value="A1|A2" /> 

下面是我的XSLT &我知道这是格式不正确。

而且我在这个XSLT

  1. 我如何可以通过下面的功能键的配置,因为它不是在XML以下问题。
  2. 如果此方法返回false,那么我想从XSLT属性返回字符串消息,如“对不起,组合不匹配”。
  3. 我知道这有点令人困惑,但我知道这很有趣。

    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
        xmlns:msxsl="urn:schemas-microsoft-com:xslt" 
        xmlns:user="urn:my-scripts"> 
    
        <msxsl:script language="C#" implements-prefix="user"> 
        <![CDATA[ 
        public string checkCategory (string category1,string category2) 
        { 
        if((category1=="Category1_A" && category1==" Category2_B") && ConfigurationManager.AppSetting["Code"].contains("A1")) 
         return true; 
         else 
         return false; 
        } 
         ]]> 
        </msxsl:script> 
        <xsl:template match="master"> 
        <child> 
         <circumference> 
         <xsl:value-of select="user: checkCategory (category1,category2)"/> 
         <!--if method return false then : return Sorry, Combination doesn’t match.”--> 
         </circumference> 
        </child> 
        </xsl:template> 
    </xsl:stylesheet> 
    
+0

从您发布的东西,它看起来像你想的XML内容到配置字符串比较,而不是其他。你为什么要用XSLT做这件事,而不是其他任何XML处理技术? – 2013-03-06 21:17:35

+0

@安妮:它是以前在项目中实现的逻辑,我正在对此进行一些更改。 – intelliWork 2013-03-07 05:24:29

如果你的函数返回truefalse,那么你应该返回类型更改为bool

<msxsl:script language="C#" implements-prefix="user"> 
    <![CDATA[ 
    public bool checkCategory (string category1,string category2) 
    { 
     if((category1=="Category1_A" && category2==" Category2_B") && ConfigurationManager.AppSetting["Code"].contains("A1")) 
     return true; 
     else 
     return false; 
    } 
    ]]> 
</msxsl:script> 

,并可以简化代码位:

<msxsl:script language="C#" implements-prefix="user"> 
    <![CDATA[ 
    public bool checkCategory (string category1,string category2) 
    { 
     return (category1 == "Category1_A" && category2 == "Category2_B") && 
       ConfigurationManager.AppSetting["Code"].contains("A1"); 
    } 
    ]]> 
</msxsl:script> 

然后你可以使用一个xsl:if

<xsl:template match="master"> 
    <child> 
     <circumference> 
     <xsl:if select="user:checkCategory(category1,category2)"> 
      <xsl:text>Sorry, Combination doesn’t match.</xsl:text> 
     </xsl:if> 
     </circumference> 
    </child> 
    </xsl:template> 
+0

当您尝试编辑我的答案时,您将此注释置于我的答案中:“我已修改:第二个是category2 ..但仍然如何使用ConfigurationManager.AppSetting [”Code“]。contains(”A1“))在xslt中,因为它不存在于XML中?“你有没有尝试使用完整的命名空间到配置管理器类?否则,您可以尝试将该值作为XSLT参数传递给XSLT。 – JLRishe 2013-03-07 05:38:47

+0

你可以在ConfigurationManager.AppSetting [“Code”]。contains(“A1”)。 – intelliWork 2013-03-07 17:46:05