我想删除最后一个元素,然后放入其他元素而不是它。
我制作了一些虚构的代码(**它不是工作的**)。
我想重复使用它的上半部分,因为它们太长而且一直在变化。
如何制作真实的?
谢谢!
var orignalTREE = new XDocument(
new XElement( "Root", new XAttribute("Id", "0"),
new XElement( "One", new XAttribute("Id", "1"),
new XElement( "Two", new XAttribute("Id", "2"),
new XElement( "Three", new XAttribute("Id", "3"),
new XElement( "Four", new XAttribute("Id", "4"),
new XElement( "Five", new XAttribute("Id", "5"),
new XElement("Six", new XAttribute("Id", "6"),
new XElement("Seven", new XAttribute("Id", "7"),
new XElement( "LAST", "It will be removed")
)))))))));
var extractedELMNT = orignalTREE.ElementsBeforeSelf("LAST");
orignalTREE.Descendants("LAST").Remove();
var modifiedTREE = new XDocument(
new XElement(
extractedELMNT.Select(x =>x),
new XElement( "Modified", new XAttribute("Testing...")
)));
MessageBox.Show( "Removed\n\n" + orignalTREE.ToString() +"\n\n\n"+
"Recovered\n\n" + modifiedTREE.ToString());
[添加]
我想改变这一个的结果;
<Root Id="0">
<One Id="1">
<Two Id="2">
<Three Id="3">
<Four Id="4">
<Five Id="5">
<Six Id="6">
<Seven Id="7">
<LAST>It will be removed</LAST>
</Seven>
</Six>
</Five>
</Four>
</Three>
</Two>
</One>
</Root>
到这一个。
<Root Id="0">
<One Id="1">
<Two Id="2">
<Three Id="3">
<Four Id="4">
<Five Id="5">
<Six Id="6">
<Seven Id="7">
<Modified>Testing..</Modified>
</Seven>
</Six>
</Five>
</Four>
</Three>
</Two>
</One>
</Root>
一般来说。
答案 0 :(得分:1)
试试这个: 的更新强>
var orignalTREE = new XDocument(
new XElement("Root", new XAttribute("Id", "0"),
new XElement("One", new XAttribute("Id", "1"),
new XElement("Two", new XAttribute("Id", "2"),
new XElement("Three", new XAttribute("Id", "3"),
new XElement("Four", new XAttribute("Id", "4"),
new XElement("Five", new XAttribute("Id", "5"),
new XElement("Six", new XAttribute("Id", "6"),
new XElement("Seven", new XAttribute("Id", "7"),
new XElement("LAST", "It will be removed")
)))))))));
var modifiedTREE = new XDocument(orignalTREE);
var parent = modifiedTREE.Descendants("LAST").FirstOrDefault().Parent;
modifiedTREE.Descendants("LAST").Remove();
parent.Add(new XElement("Modified", "Its attribute"));
Console.WriteLine("Removed\n\n" + orignalTREE.ToString() + "\n\n\n" +
"Recovered\n\n" + modifiedTREE.ToString());