如何在c#中使用linq从xml元素中添加自定义属性值

本文关键字:元素 xml 添加 自定义属性 linq | 更新日期: 2023-09-27 18:03:33

您好,我有一个xml文档

<task>
<directory path="C:'Backup'"/>
<days value="2" />
</task>

我想在c#中使用linq获得目录的路径和days值,我该如何实现这一点?

The output should be 
C:'Backup' and 2

到目前为止,我已经尝试了下面的xdocument是我的xml文件的路径,它工作良好

              var directory = xdocument.Descendants("task")
                              .Elements("directory")
                              .Attributes("path");

但这部分不起作用。

如何在c#中使用linq从xml元素中添加自定义属性值

你可以试试:

var directory = xdoc.DescendantsAndSelf("task") 
                  .Select(c => new 
                  {
                    Path = c.Elements("directory").Attributes("path").First().Value,
                    Day = c.Elements("days").Attributes("value").First().Value,
                  });

或者如果你想要一个字符串:

var directory = xdoc.DescendantsAndSelf("task") 
                  .Select(c => new 
                  {
                    Complete = c.Elements("directory").Attributes("path").First().Value +
                    c.Elements("days").Attributes("value").First().Value
                  });

编辑你可以像这样遍历它们:

foreach(var item in directory)
{
   Console.WriteLine(item.Path+ " + item.Day);
}

检查这个,因为Descendants()Elements()返回IEnumerable的结果

var directory = xdocument.Descendants("task").First().
                              .Elements("directory").First().
                              .Attribute("path").Value;
相关文章: