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,
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>
