2015-04-06 28 views
0

我必須使用輸入xml中可用的數據創建實體對象。此對象的屬性之一的值取決於一個條件,它看起來像這樣的XPath:使用XPath的C#中的條件表達式

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'else'N''有一個無效的標記。

所以我的問題是:

  1. 是在C#/支持這一條件表達式網(4.5)?
  2. 如果不是,當我們必須檢查XPath中的多個條件時,推薦的方法是什麼?

感謝 迪利普

+0

在XPath 1.0中沒有'if',.NET僅支持XPath 1.0。請參閱http://stackoverflow.com/questions/971067/is-there-an-if-then-else-statement-in-xpath?rq=1瞭解可能的解決方案 – xanatos 2015-04-06 13:31:07

回答

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的變化。

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:when>條件的XSL代碼。