0

我对一个问题感到震惊。请帮帮我。

我有一个xml

      <Set type="Main">
          <FirstUnit xmlns:i="http://www.w3.org/2001/XMLSchema-instance" z:Id="i1" xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/">
            <CreateDate>2013-06-06T13:19:17.457</CreateDate>
            <PrimaryKey>1</PrimaryKey>
          </FirstUnit>
          <Secondunit  xmlns:i="http://www.w3.org/2001/XMLSchema-instance" z:Id="i1" xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/">
            <CreateDate>2013-06-06T13:19:17.457</CreateDate>
            <PrimaryKey>1</PrimaryKey>
            <Exercise>Test</Exercise>
          </SecondUnit>
          <FirstUnit xmlns:i="http://www.w3.org/2001/XMLSchema-instance" z:Id="i1" xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/">
            <CreateDate>2013-06-06T13:19:17.457</CreateDate>
            <PrimaryKey>2</PrimaryKey>
          </FirstUnit>
          <Secondunit  xmlns:i="http://www.w3.org/2001/XMLSchema-instance" z:Id="i1" xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/">
            <CreateDate>2013-06-06T13:19:17.457</CreateDate>
            <PrimaryKey>2</PrimaryKey>
            <Exercise>Test</Exercise>
          </SecondUnit>
     </Set>

现在我想要的只是根据主键对单元进行分组。即 FirstUnit 和 SecondUnit 应该在一个组中具有<Primarykey>节点值“1”,在另一组中具有PrimaryKey节点值“2”。

我已经用下面的查询试过了,还需要做更多的改进,

var elements = xDocument.GroupBy(a => a.Elements().Descendants().Where(x => x.Name.LocalName == "PrimaryKey" ).ToList());

提前致谢。

4

1 回答 1

1

在我看来,您只需要按这些元素的值进行分组:

// If <Set> is the document element, change Descendants("Set") to Root
var elements = xDocument.Descendants("Set")
                        .Elements()
                        .GroupBy(x => (int) x.Element("PrimaryKey"));

(如有必要,为元素提供命名空间 - 使用Where子句仅检查本地名称有点难看。)

如果这对您不起作用,请提供有关您正在尝试做的事情的更多详细信息。

于 2013-06-21T10:54:54.083 回答