0

I've to create an entity object using the data available from an input xml. The value of one of the properties of this object depends on a condition and it looks like this in XPath :

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

And the below function takes this XPath and the xml document :

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

However, it doesn't work. The error is :

'if (//trade/tradeHeader/tradeTypology/tradeCategoryTypology[tradeCategory = 'TechnicalCancellation']) then 'Y' else 'N'' has an invalid token.

So my questions are :

  1. Is this conditional expression supported in C#/.Net (4.5) ?
  2. If not, what's the recommended approach when we have to check for multiple conditions in XPath ?

Thanks Dileep

  • There is no `if` in XPath 1.0, .NET supports only XPath 1.0. See http://stackoverflow.com/questions/971067/is-there-an-if-then-else-statement-in-xpath?rq=1 for a possible solution – xanatos Apr 06 '15 at 13:31

2 Answers2

0

You can wrie XPath this way:

<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>

You can have a lot of <xsl:when> conditions in your XSL code.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
0

XPath 1.0 does not have conditionals (and vanilla .NET only supports XPath 1.0).

However, I don't see the point in selecting "Y" or "N" in XPath when you actually can use the host language, so what's wrong with

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";
}

?

If you absolutely, positively have to do it with XPath, you can use

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

which is a variation of my answer in the thread @xanatos mentions in the comments.

Community
  • 1
  • 1
Tomalak
  • 332,285
  • 67
  • 532
  • 628