How to cast XPathEvalute when it can be XElement or XAttribute?

前端 未结 4 1891
自闭症患者
自闭症患者 2021-02-20 06:29

So I have this code:

List prices =
                (from item in xmlDoc.Descendants(shop.DescendantXName)
                 select new PriceDet         


        
4条回答
  •  醉梦人生
    2021-02-20 06:50

    Dimitre's solution returns empty string if the element is not found; we can't distinguish it from actual empty value. So I had to make this extension method that handles multiple results by XPath query and returns empty enumeration if nothing is found:

    public static IEnumerable GetXPathValues(this XNode node, string xpath)
    {
        foreach (XObject xObject in (IEnumerable)node.XPathEvaluate(xpath))
        {
            if (xObject is XElement)
                yield return ((XElement)xObject).Value;
            else if (xObject is XAttribute)
                yield return ((XAttribute)xObject).Value;
        }
    }
    

提交回复
热议问题