当XPathEvalute可以是XElement或XAttribute时,如何转换? [英] How to cast XPathEvalute when it can be XElement or XAttribute?

查看:27
本文介绍了当XPathEvalute可以是XElement或XAttribute时,如何转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有这段代码:

List<PriceDetail> prices =
                (from item in xmlDoc.Descendants(shop.DescendantXName)
                 select new PriceDetail
                 {
                     Price = GetPrice(item.Element(shop.PriceXPath).Value),
                     GameVersion = GetGameVersion(((IEnumerable)item.XPathEvaluate(shop.TitleXPath)).Cast<XAttribute>().First<XAttribute>().Value, item.Element(shop.PlatformXPath).Value),
                     Shop = shop,
                     Link = item.Element(shop.LinkXPath).Value,
                     InStock = InStock(item.Element(shop.InStockXPath).Value)
                 }).ToList<PriceDetail>();

我的问题是这段代码:

((IEnumerable)item.XPathEvaluate(shop.TitleXPath)).Cast<XAttribute>().First<XAttribute>().Value

有时XPathEvaluate中的对象可能是XElement,然后强制转换不起作用.因此,我需要一个可以同时使用XAttribute和XElement的Cast.

Sometimes the object from XPathEvaluate could be XElement and then the casting doesn't work. So what I need is a Cast that works with both XAttribute and XElement.

有什么建议吗?

推荐答案

更改XPath表达式( shop.TitleXPath ):

Change your XPath expression (shop.TitleXPath) from:

  someXPathExpression

:

  string(someXPathExpression)

然后,您可以将代码简化为:

string result = item.XPathEvaluate(shop.TitleXPath) as string;


完整的工作示例:

using System;
using System.IO;
using System.Xml.Linq;
using System.Xml.XPath;

class TestXPath
{
    static void Main(string[] args)
    {

        string xml1 =
@"<t>
 <a b='attribute value'/> 
 <c>
   <b>element value</b>
 </c>
 <e b='attribute value'/>
</t>";

        string xml2 =
@"<t>
 <c>
   <b>element value</b>
 </c>
 <e b='attribute value'/>
</t>";

        TextReader sr = new StringReader(xml1);
        XDocument xdoc = XDocument.Load(sr, LoadOptions.None);

        string result1 = xdoc.XPathEvaluate("string(/*/*/@b | /*/*/b)") as string;

        TextReader sr2 = new StringReader(xml2);
        XDocument xdoc2 = XDocument.Load(sr2, LoadOptions.None);

        string result2 = xdoc2.XPathEvaluate("string(/*/*/@b | /*/*/b)") as string;

        Console.WriteLine(result1);
        Console.WriteLine(result2);


    }
}

执行该程序时,相同的XPath表达式将应用于两个不同的XML文档,并且无论 string()的参数是第一次属性还是元素在第二个步骤中,我们得到了正确的结果-写入控制台:

When this program is executed, the same XPath expression is applied on two different XML documents and, regardless of the fact that the argument to string() is an attribute the first time and is an element on the second, we get the correct results -- written to the Console:

attribute value
element value

这篇关于当XPathEvalute可以是XElement或XAttribute时,如何转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆