Please consider this 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>
That is content of a XElement
variable.Now I have another XElement
variable with this content:
<Person>
<ID>1001</ID>
<Name>Aba</Name>
<LName>Aba</LName>
</Person>
I want to add this XEelemnt
variable to first XElement
in a specific position (for example as second Person
tag). How I can do this?
thanks
First you need to load the xml string, second you get the position where you want to insert the xml, then insert the new xml. Here is an example how to do it.
var reader = new StringReader(@"<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>");
var xdoc = XDocument.Load(reader);
xdoc.Element("Employees").
Elements("Person").
First().
AddAfterSelf(new XElement("Person",
new XElement("ID", 1001),
new XElement("Name", "Aba"),
new XElement("LName", "Aba")));
var sb = new StringBuilder();
var writer = new StringWriter(sb);
xdoc.Save(writer);
Console.WriteLine(sb);
If you want to insert by index, just get the element first. For example you want to insert as second position, then you need to get the first index (index = 0).
var xdoc = XDocument.Load(reader);
xdoc.Element("Employees").
Elements("Person").
ElementAt(0).
AddAfterSelf(new XElement("Person",
new XElement("ID", 1001),
new XElement("Name", "Aba"),
new XElement("LName", "Aba")));
PS: For simplicity purpose I didn't add nullity check.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With