使用求和条件XPATH C#的SelectNodes

时间:2019-03-09 14:50:00

标签: c# xml xpath sum

我正在尝试进行一些查询,以返回在整个季节中电视节目数量都超过电视节目数量的电视节目。 我有获取XMLDoc和金额的功能。

我试图这样做,但是出了点问题:

   public XmlNodeList Query7(XmlDocument xmlDoc, int amountOfEpisodes)// 
            {
                string s = "Netflix/TV-shows/TV-show[sum(seasons)>"+amountOfEpisodes+"]";
                XmlNodeList xmlNodeList = xmlDoc.SelectNodes(s);
                return xmlNodeList;
            }

XMLDoc:

<Netflix>
  <TV-shows>
    <TV-show>
          <name>Game of Thrones</name>
          <genre>Action</genre>
          <year>2011</year>
          <seasons>
            <season>
              <episodes>10</episodes>
            </season>
            <season>
              <episodes>10</episodes>
            </season>
            <season>
              <episodes>10</episodes>
            </season>
            <season>
              <episodes>10</episodes>
            </season>
            <season>
              <episodes>10</episodes>
            </season>
            <season>
              <episodes>10</episodes>
            </season>
            <season>
              <episodes>7</episodes>
            </season>
          </seasons>
        </TV-show>
        <TV-show>
          <name>The Sopranos</name>
          <genre>Crime</genre>
          <year>1999</year>
          <seasons>
            <season>
              <episodes>13</episodes>
            </season>
            <season>
              <episodes>13</episodes>
            </season>
            <season>
              <episodes>13</episodes>
            </season>
            <season>
              <episodes>13</episodes>
            </season>
            <season>
              <episodes>13</episodes>
            </season>
            <season>
              <episodes>21</episodes>
            </season>
          </seasons>
        </TV-show>
        <TV-show>
 </TV-shows>
</Netflix>

例如,在我上面的XML中,输入“ 70”的结果应仅为 “女高音”是因为70集以上的情节仅出现在女高音中。

感谢帮助

2 个答案:

答案 0 :(得分:2)

您的xpath无效,因为总和(季节)没有任何意义,因为季节不是数字。您可以通过计数(季节)来获取季节计数,但这不是您想要的。相反,您需要几集的总和,因此需要选择几集:

/ Netflix /电视节目/电视节目[总和(季节/季节/情节)>“ +情节数量+”]“

答案 1 :(得分:-1)

使用xml linq:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            var results = doc.Descendants("TV-show").Select(x => new
            {
                name = (string)x.Element("name"),
                episodes = x.Descendants("episodes").Count()
            }).ToList();


        }
    }
}