How to insert a child tag using XDocument and XElement?

Viewed 89

I have this xml schema which I need to add a child tag to:

<?xml version="1.0" encoding="utf-8"?>
<PFA>
  <Entity id="123" action="add" date="04-Nov-2017"></Entity>
  <Entity id="125" action="add" date="05-Nov-2017"></Entity>
</PFA>

and the expected result is:

<?xml version="1.0" encoding="utf-8"?>
<PFA>
  <Record>
  <Entity id="123" action="add" date="04-Nov-2017"></Entity>
  <Entity id="125" action="add" date="05-Nov-2017"></Entity>
  </Record>
</PFA>

I have tried with this code:

var doc = XDocument.Load("data.xml");
var record = new XElement("Record");
doc.Element("PFA").Add(record);
doc.Save("data.xml");

But my result is below. It has the closing tag, but it's missing the opening tag.

<?xml version="1.0" encoding="utf-8"?>
<PFA>
  <Entity id="123" action="add" date="04-Nov-2017">
   
  </Entity>
  </Record>
</PFA>

Updated:

I tried this solution with Elements:

var doc = XDocument.Load(file.FullName);
var record = new XElement("Record");
var pfa = doc.Element("PFA");
var entities = pfa.Elements("Entity");
entities.Remove();    // remove <Entity> from <PFA>
pfa.Add(record);    // add <Record> to <PFA>
record.Add(entities); // add <Entity> to <Record>
doc.Save(file.FullName);

But still the opening record tag is missing,

enter image description here

and the output becomes:

<?xml version="1.0" encoding="utf-8"?>
<PFA>
  <Record />
</PFA>

If I use Element:

var doc = XDocument.Load(file.FullName);
var record = new XElement("Record");
var pfa = doc.Element("PFA");
var entities = pfa.Element("Entity");
entities.Remove();    // remove <Entity> from <PFA>
pfa.Add(record);    // add <Record> to <PFA>
record.Add(entities); // add <Entity> to <Record>
doc.Save(file.FullName);

The output becomes:

<?xml version="1.0" encoding="utf-8"?>
<PFA>
  <Entity id="123" action="add" date="04-Nov-2017"></Entity></Record>
  <Record><Entity id="123" action="add" date="04-Nov-2017"></Entity></Record>
  <Record><Entity id="125" action="add" date="05-Nov-2017"></Entity></Record>
</PFA>
1 Answers

The solution is actually quite easy. You remove the Entity tags from the PFA tag, then add the new Record tag to the PFA tag and readd the Entity tags to the new added Record tag. The code might look like this:

var pfa = doc.Element("PFA");
IList<XElement> entities = pfa.Elements("Entity").ToList();
foreach (var entity in entities)
{
    entity.Remove(); // Remove all the <Entity> tags from <PFA>
}
var record = new XElement("Record");
pfa.Add(record); // Add the new <Record>
foreach (var entity in entities) 
{
    record.Add(entity); // Add the <Entity> tags back to <Record>
}
Related