使用嵌套linq的xml进行分类

问题描述 投票:0回答:1

我有一个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

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

现在,我正在尝试将此结构加载到UnlinkCommand对象的列表中,看起来像这样:

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查询中获得的信息是否可能。

c# xml linq linq-to-xml
1个回答
1
投票

您可以使用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()
                                 }
   );

样本输出

enter image description here


0
投票

使用LINQ to XML查询子元素非常简单。由于在LINQ查询中创建包装类时通常位于元素节点,因此在分配给列表时只需查询嵌套元素。使用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()
    });
© www.soinside.com 2019 - 2024. All rights reserved.