当 XPathEvalute 可以是 XElement 或 XAttribute 时,如何强制转换?

2024-04-22

所以我有这个代码:

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。

有什么建议吗?


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

  someXPathExpression

to:

  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()第一次是一个属性,第二次是一个元素,我们得到了正确的结果——写入控制台:

attribute value
element value
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

当 XPathEvalute 可以是 XElement 或 XAttribute 时,如何强制转换? 的相关文章

随机推荐