C#中使用XPath的条件表达式
我必须使用输入xml中可用的数据创建实体对象。此对象的一个属性的值取决于一个条件,在XPath中如下所示:C#中使用XPath的条件表达式,c#,if-statement,xpath,conditional-statements,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 xD
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;
}
但是,它不起作用。错误是:
'如果(//trade/tradeHeader/tradeTypeology/tradeCategoryTypeology[tradeCategory='TechnicalCancellation']),则'Y'else'N'具有无效令牌
因此,我的问题是:
Dileep您可以这样编写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代码中可以有很多条件。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,那么可以使用
子串(
“NY”,
计数(
//贸易/贸易标题/贸易类型学/贸易类别学[tradeCategory='TechnicalCancellation'][1]
) + 1,
1.
)
这是我答案的一个变体。XPath 1.0中没有
if
,.NET只支持XPath 1.0。有关可能的解决方案,请参阅