Linq to XML - 删除节点并在同一位置添加新节点

chu*_*h97 5 linq-to-xml

我有一个XDocument并且必须删除一个节点并在一些操作之后再次添加相同的节点(我的xelement节点很复杂并且还有内部节点).有没有人有一个很好的方法来做这个,因为我的新操作节点被添加到xmldocument的最后.任何代码片段都将非常感激.

Ral*_*lle 8

如果我理解你的话,这应该可以帮到你.

SolarSystem.xml:

<?xml version="1.0" encoding="UTF-8"?>
<SolarSystem>
  <Planets>
    <Planet Id="1">
      <Name>Mercury</Name>
    </Planet>
    <Planet Id="2">
      <Name>Venus</Name>
    </Planet>
    <Planet Id="3">
      <Name>Earth</Name>
    </Planet>
  </Planets>
</SolarSystem>
Run Code Online (Sandbox Code Playgroud)

代码找到了<Planet>Mercury,为它添加了一个额外的元素,将其删除,并在<Planets>集合的末尾重新插入它.

XDocument SolarSystem = XDocument.Load(Server.MapPath("SolarSystem.xml"));
IEnumerable<XElement> Planets = SolarSystem.Element("SolarSystem").Element("Planets").Elements("Planet");

// identify and change Mercury
XElement Mercury = Planets.Where(p => p.Attribute("Id").Value == "1").FirstOrDefault();
Mercury.Add(new XElement("YearLengthInDays", "88"));

// remove Mercury from current position, and add back in at the end
Mercury.Remove();
Planets.Last().AddAfterSelf(Mercury);

// save it as new file
SolarSystem.Save(Server.MapPath("NewSolarSystem.xml"));
Run Code Online (Sandbox Code Playgroud)

这使:

<?xml version="1.0" encoding="UTF-8"?>
   <SolarSystem>
     <Planets>
       <Planet Id="2">
         <Name>Venus</Name>
       </Planet>
       <Planet Id="3">
         <Name>Earth</Name>
       </Planet>
       <Planet Id="1">
         <Name>Mercury</Name>
         <YearLengthInDays>88</YearLengthInDays>
       </Planet>
     </Planets>
   </SolarSystem>
Run Code Online (Sandbox Code Playgroud)


Pav*_*aev 4

如果您只是编辑节点,那么为什么要删除它呢?只需在树中获取对它的引用并就地编辑即可。

如果由于某种原因这不是一个选项,那么一种解决方法是:一旦您在树中找到了需要替换的XElement(或者一般来说, ),创建一个新的作为替换,然后然后在旧元素上使用方法,传递新元素作为参数。XNodeXElementXNode.ReplaceWith