无法使用 xPathNavigator 从 xml 获取列表

Unable to get list from xml using xPathNavigator

List<string> list = new List<string>();
foreach (XPathNavigator node in nav.Select("configuration/company/work/worktime"))
            {
                string day = getAttribute(node, "day");
                string time = getAttribute(node, "time");
                string worktype = ?? // how to get worktype attribute valuefrom parent node 
              list.Add(day,time,worktype); // add to list 
            }

 </configuration>
      <company>
        <work worktype="homeWork">
            <worktime day="30" time="10:28"></worktime>
            <worktime day="25" time="10:50"></worktime>
         </work>
        <work worktype="officeWork">
            <worktime day="12" time="09:28"></worktime>
            <worktime day="15" time="12:28"></worktime>
        </work>
      </company>
    </configuration>


need output as :
list[0] = homeWork,30,10:28
list[1] = homeWork,25,10:50
list[2] = officeWork,12,09:28
list[3] = officeWork,15,12:28

我正在尝试从 XML 获取列表,但未能获得如上所示的输出(使用 xpath 导航器,如何访问父节点以获取工作类型属性,以及其他剩余的内部节点属性?

使用嵌套循环。最初使用 configuration/company/work 检索工作节点。检索工作类型属性并存储在变量中。然后遍历子工作类型节点并为每个节点添加一个字符串到列表中

使用 Net Library 增强 xml (linq xml)

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("work").Select(x => new {
                worktype = (string)x.Attribute("worktype"),
                worktime = x.Elements("worktime").Select(y => new {
                    day = (int)y.Attribute("day"),
                    time = (DateTime)y.Attribute("time")
                }).ToList()
            }).ToList();
        }
    }
}

我建议在 XPath 上使用 LINQ to XML,但是如果你必须使用 XPathNavigator 那么你需要迭代每个 work 元素,然后是它的每个 worktime 子元素。这样您就可以使用父上下文中的 worktype

foreach (XPathNavigator work in nav.Select("configuration/company/work"))
{
    var workType = work.GetAttribute("worktype", string.Empty);

    foreach (XPathNavigator worktime in work.Select("worktime"))
    {
        var day = worktime.GetAttribute("day", string.Empty);
        var time = worktime.GetAttribute("time", string.Empty);

        list.Add($"{workType}, {day}, {time}");
    }
}

有关工作演示,请参阅 this fiddle