【问题标题】:Add XElement to list and have it's children be remainder of list将 XElement 添加到列表并让它的子元素成为列表的剩余部分
【发布时间】:2020-02-27 16:23:34
【问题描述】:

如果我有以下 xml:

<Employees>
<Person>
    <ID>1000</ID>
    <Name>Nima</Name>
    <LName>Agha</LName>
</Person>
<Person>
    <ID>1002</ID>
    <Name>Ligha</Name>
    <LName>Ligha</LName>
</Person>
<Person>
    <ID>1003</ID>
    <Name>Jigha</Name>
    <LName>Jigha</LName>
</Person>
</Employees>

我想在索引节点之后添加一个新节点,并将剩余的人节点添加为这个新节点的子节点。

所以添加后的新xml如下所示:

<Employees>
<Person>
    <ID>1000</ID>
    <Name>Nima</Name>
    <LName>Agha</LName>
</Person>
<RefNode>
    <Person>
        <ID>1002</ID>
        <Name>Ligha</Name>
        <LName>Ligha</LName>
    </Person>
    <Person>
        <ID>1003</ID>
        <Name>Jigha</Name>
        <LName>Jigha</LName>
    </Person>
</RefNode>
</Employees>

到目前为止,我已经尝试过使用

ElementAt(index).AddAfterSelf()

但这只是将它添加到下一行,并没有将接下来的两个 Person 添加为子项。

【问题讨论】:

  • 分两步完成。首先创建新的 XElement AfterSelf。然后将节点移动到新元素中。
  • 我想你误解了AddAfterSelf() 方法的作用,请参考这个documentation。该方法不会将下一个节点作为新添加节点的子节点移动。

标签: c# xml linq-to-xml


【解决方案1】:

您可以执行以下操作。在代码中添加了 cmets 以便更好地理解

var xdoc = XDocument.Parse(xml);

// Unclear how you are identifying the node after which the change has to happen. For sake of example, using ID
var selectedNode = xdoc.Descendants("Person")
                       .First(x=>Convert.ToInt32(x.Element("ID").Value)==1000);

// Collection of nodes that would be added as child of newly inserted node
var nodeAfterSelectedNode = xdoc.Descendants("Person")
                                .SkipWhile(x=>x==selectedNode) 
                                .ToList();

// Create the new node with previously identified 'nodeAfterSelectedNode' as Children
var newElement = new XElement("RefNode",nodeAfterSelectedNode);

// Remove the existing Nodes (ones that are being moved to child) 
foreach(var node in nodeAfterSelectedNode)
{
   node.Remove();
}
// add the new node 
selectedNode.AddAfterSelf(newElement);
var newXml = xdoc.ToString();

输出

<Employees>
  <Person>
    <ID>1000</ID>
    <Name>Nima</Name>
    <LName>Agha</LName>
  </Person>
  <RefNode>
    <Person>
      <ID>1002</ID>
      <Name>Ligha</Name>
      <LName>Ligha</LName>
    </Person>
    <Person>
      <ID>1003</ID>
      <Name>Jigha</Name>
      <LName>Jigha</LName>
    </Person>
  </RefNode>
</Employees>

输出样本

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-13
    • 1970-01-01
    相关资源
    最近更新 更多