xml 到 class 使用嵌套 linq

xml to class using nested linq

我有一个 XML 结构,看起来像这样:

<Commands>
  <Command id="Prefix" classId="prefix">
    <ShortDescription>A Command</ShortDescription>
    <LongDescription>A Prefix Command</LongDescription>
    <Subcommands>
      <CommandReference commandID="PrefixQuery" syntax="query"></CommandReference>
      <CommandReference commandID="PrefixRevert" syntax="revert"></CommandReference>
      <CommandReference commandID="PrefixSet" syntax="set"></CommandReference>
    </Subcommands>
  </Command>
</Commands

它用于在加载程序时创建命令层次结构。

现在,我正在尝试将此结构加载到 UnlinkedCommand 对象列表中,如下所示:

struct UnlinkedCommand
{
  public string commandID;
  public string commandClassID;
  public string shortDescription;
  public string longDescription;
  public List<CommandReference> subcommands;
}

CommandReference 如下所示:

struct CommandReference
{
  public string commandID;
  public string syntax;
}

我一直在研究如何创建一个嵌套的 Linq 查询,它可以在查询命令列表的同时创建子命令列表,我不确定它是否可能从我读到的关于 Linq 查询的内容来看。

您可以使用Linq查询如下

XElement command = XElement.Parse(xml);
var result = command.Descendants("Command").Select(x=> new UnlinkedCommand
    {
    commandID = x.Attribute("id").Value,
    commandClassID = x.Attribute("classId").Value,
    shortDescription = x.Element("ShortDescription").Value,
    longDescription= x.Element("LongDescription").Value,
    subcommands = x.Element("Subcommands")
                   .Descendants("CommandReference")
                   .Select(c=> new CommandReference
                                 {  
                                   commandID = c.Attribute("commandID").Value, 
                                   syntax = c.Attribute("syntax").Value}).ToList()
                                 }
   );

示例输出

使用 LINQ to XML 查询子元素非常简单。由于在 LINQ 查询中创建包装 class 时通常位于元素节点处,因此在分配给列表时只需查询嵌套元素。使用 LINQ-to-XML 解析此 XML 以获得嵌套元素看起来像这样:

var xml = @"<Commands>
  <Command id=""Prefix"" classId=""prefix"">
    <ShortDescription>A Command</ShortDescription>
    <LongDescription>A Prefix Command</LongDescription>
    <Subcommands>
      <CommandReference commandID=""PrefixQuery"" syntax=""query""></CommandReference>
      <CommandReference commandID=""PrefixRevert"" syntax=""revert""></CommandReference>
      <CommandReference commandID=""PrefixSet"" syntax=""set""></CommandReference>
    </Subcommands>
  </Command>
</Commands>";

var xdoc = XDocument.Parse(xml);
var commands = xdoc.Elements("Commands").Elements("Command")
    .Select(command => new UnlinkedCommand {
        /* get elements and attributes for other fields */
        subcommands = command.Element("Subcommands")
                             .Elements("CommandReference")
                             .Select(subcommand => new CommandReference { /* assign attributes to fields */ })
                             .ToList()
    });