2013-03-13 41 views
0

嗨,我有一个XML文档如何使用linq在c#中从xml元素添加自定义属性值?

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

我想要得到的目录,并在C#中使用LINQ我怎样才能做到这一点的日子值的路径?

The output should be 
C:\Backup\ and 2 

到目前为止我想是这样的下面的XDocument的路径是我的xml文件的正常工作

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

,但是这部分不能正常工作。任何帮助将真正被赞赏。

回答

0

你可以试试这个:

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); 
} 
+0

感谢,但它没有工作,我在想,如果它的工作原理,我将到单独的字符串它们分割。 – nzdev 2013-03-13 07:09:30

+0

@nzdev顶部的例子呢 – 2013-03-13 07:10:08

+0

@nzdev我编辑了我的答案,包括如何使用'directory'。 – 2013-03-13 07:15:11

0

检查这一点,因为Descendants()Elements()回报IEnumerable导致

var directory = xdocument.Descendants("task").First(). 
           .Elements("directory").First(). 
           .Attribute("path").Value; 
+0

抱歉把这个没有运气返回null .. – nzdev 2013-03-13 07:04:39

相关问题