2013-03-13 42 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

相關問題