使用XPath在C#中的条件表达式

时间:2015-04-06 12:54:35

标签: c# if-statement xpath conditional-statements

我将使用输入xml中提供的数据创建实体对象。此对象的某个属性的值取决于条件,它在XPath中如下所示:

if (//trade/tradeHeader/tradeTypology/tradeCategoryTypology[tradeCategory = 'TechnicalCancellation']) then 'Y' else 'N'")

以下函数采用此XPath和xml文档:

private static string GetValueFromXml(XmlDocument xDoc, string xPath)
    {
        var nod = xDoc.SelectSingleNode(xPath);
        if (nod != null)
            return nod.InnerText;
        return null;
    }

然而,它不起作用。错误是:

'if(// trade / tradeHeader / tradeTypology / tradeCategoryTypology [tradeCategory ='TechnicalCancellation'])然后'Y'其他'N''的标记无效。

所以我的问题是:

  1. C#/。Net(4.5)?
  2. 是否支持此条件表达式
  3. 如果没有,当我们必须检查XPath中的多个条件时,推荐的方法是什么?
  4. 由于 迪利普

2 个答案:

答案 0 :(得分:0)

您可以这样编写XPath:

<xsl:choose>
  <xsl:when test="//trade/tradeHeader/tradeTypology/tradeCategoryTypology[@tradeCategory ='TechnicalCancellation']">
   <xsl:value-of select="'Y'"/>
  </xsl:when>
<xsl:otherwise>
   <xsl:value-of select="'N'"/>
</xsl:otherwise>
</xsl:choose>

您的XSL代码中可能有很多<xsl:when>条件。

答案 1 :(得分:0)

XPath 1.0没有条件(并且vanilla .NET仅支持XPath 1.0)。

但是,当您真正可以使用托管语言时,我在XPath中选择"Y""N"时没有注意到这一点,那么

有什么问题?
private static string GetValueFromXml(XmlDocument xDoc, string xPath)
{
    var node = xDoc.SelectSingleNode(xPath);
    return (node != null) node.InnerText : null;
}

private static void Test()
{
    var path = "//trade/tradeHeader/tradeTypology/tradeCategoryTypology[tradeCategory = 'TechnicalCancellation']";
    var doc = GetYourXmlDocumentSomehow();

    var result = GetValueFromXml(doc, path) == null ? "N" : "Y";
}

如果绝对必须使用XPath,可以使用

substring(
  'NY', 
  count(
    //trade/tradeHeader/tradeTypology/tradeCategoryTypology[tradeCategory = 'TechnicalCancellation'][1]
  ) + 1,
  1
)

这是我的回答in the thread @xanatos mentions in the comments的变体。