【问题标题】:Moving node in xdocument在 xdocument 中移动节点
【发布时间】:2013-07-07 03:22:38
【问题描述】:

我想通过属性找到一个节点并将其移动到底部。

XNode node = doc.Root.Elements().Where(e => e.Attribute("id").Value == "123").FirstOrDefault();
if (node != null)
{
    node.Root.Elements().Where(s => e.Attribute("id").Value == "123").Remove();
    doc.Root.Add(node);
}

这并不总是有效。在 .Remove() 行上,我有时会收到 nullReferenceException。所以我猜这意味着它匹配并在 FirstOrDefault() 上获得了一个节点,但随后两行完全相同的 linq 查询没有匹配任何内容。没有看到这是怎么可能的。我错过了什么吗?没有任何东西同时触及这个文件或任何东西。

【问题讨论】:

标签: c# .net linq linq-to-xml


【解决方案1】:

请使用这个sample:

 var foos = (from xElem in xDoc.Root.Descendants("Foo")
                       where xElem.Attribute("id").Value == "2" || xElem.Attribute("id").Value == "3"
                       select xElem).ToList();

            var newParentElem = (from xElem in xDoc.Root.Descendants("SubSection")
                                where xElem.Attribute("id").Value == "C"
                                select xElem).Single();

            foreach(var xElem in foos)
            {
                xElem.Remove();
                newParentElem.Add(xElem);
            }

【讨论】:

  • 很公平,但我的问题要简单得多。我想将一个节点移动到同一个父节点内的底部。为什么我的代码不起作用?
  • 实际上,我所做的与此相同,除了我使用 singleordefault() 而不是 single 然后检查 null 情况,因为在我的情况下节点可能不存在
猜你喜欢
  • 2023-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多