C#使用linq反序列化xml

时间:2017-07-05 23:41:07

标签: c# xml linq xml-deserialization

我有以下xml文件

<?xml version="1.0" encoding="utf-8"?>
<Launchpad>
  <Shortcuts>
    <Shortcut Id="1">
      <Type>Folder</Type>
       <FullPath>C:\bla\bla\bla</FullPath>
       <Name>Proximity</Name>
    </Shortcut>
    <Shortcut Id="2">
      <Type>Folder</Type>
      <FullPath>C:\bla</FullPath>
      <Name>Visual Studio 2017</Name>
    </Shortcut>
  </Shortcuts>
</Launchpad>

我正在尝试反序列化为这样的对象:(首先尝试查询语法,也没有工作)

XDocument xd = XDocument.Load(FullPath);

// query syntax
//var shortcuts = (from s in xd.Descendants("Shortcuts")
//                 select new Shortcut()
//                 {
//                   Id = Convert.ToInt32(s.Attribute("Id")),
//                   TypeOfLink = GetTypeFromString(s.Descendants("Type") 
//                                .First()
//                                .Value),
//                   FullPathToTarget = s.Descendants("FullPath") 
//                                         .First()
//                                         .Value,
//                   Name = s.Descendants("Name").First().Value,
//                 }).ToList();

// method syntax
List<Shortcut> shortcuts = xd.Descendants("Shortcuts")
                             .Select(s => 
               new Shortcut()
               {
                 //Id = Convert.ToInt32(s.Attribute("Id")),
                 TypeOfLink = GetTypeFromString(s.Descendants("Type") 
                                                 .First().Value),
                 FullPathToTarget = s.Descendants("FullPath")
                                                 .First().Value,
                 Name = s.Descendants("Name")
                         .First().Value,
               }).ToList();
return shortcuts;

出于某种原因,我只在列表中获得一个快捷方式对象。此外,由于某种原因,s.Attribute(&#34; Id&#34;)为空。

如果有人有任何建议来改善linq查询或者为什么该属性不起作用,那将是一个很大的帮助

2 个答案:

答案 0 :(得分:3)

你必须阅读.Descendants(&#34; Shortcut&#34;)而不是.Descendants(&#34; Shortcuts&#34;)。 像这样:

List<Shortcut> shortcuts = xd.Descendants("Shortcut").Select(s =>
                       new Shortcut()
                       {
                           Id = s.Attribute("Id").Value, 
                           TypeOfLink = s.Descendants("Type").First().Value,
                           FullPathToTarget = s.Descendants("FullPath").First().Value,
                           Name = s.Descendants("Name").First().Value,
                       }).ToList();

答案 1 :(得分:1)

我选择false作为Shortcut的后代来获取完整列表。

此外,Shortcuts是一个XAttribute,因此您无法将其转换为int。

您需要使用ID来获取属性值。

Value