I'm fairly new to XML and C#, so please understand if this question is too sily to ask.
I'm converting XML format using C# win-form application. The app opens a xml file using 'OpenFileDialog', then conversion will be excuted(this is already done, but I still need to add or remove some more like below) . After conversion, the app will save the modified xml file using 'SaveFileDialog'.
Original XML Format
<?xml version="1.0" encoding="utf-8" ?>
<DataList>
<Data>
<ID>1</ID>
<Name>Mike</Name>
<Age>23</Age>
</Data>
<Data>
<ID>1</ID>
<Name>Mike</Name>
<Age>23</Age>
</Data>
<Data>
<ID>1</ID>
<Name>Mike</Name>
<Age>23</Age>
</Data>
..<Data></Data> continued...
</DataList>
I want to edit the XML file as below
<?xml version="1.0" encoding="utf-8" ?> **→ Remove this delaration!**
<MainInterface> **→ Add 'root element' before existing nodes**
<DataList>
<Data>
<ID>1</ID>
<Name>Mike</Name>
<Age>23</Age>
</Data>
<Data>
<ID>1</ID>
<Name>Mike</Name>
<Age>23</Age>
</Data>
<Data>
<ID>1</ID>
<Name>Mike</Name>
<Age>23</Age>
</Data>
..<Data></Data> continued...
</DataList>
</MainInterface> **→ close newly added root element**
I've tried below code but seem like it doesn't work
OpenFileDialog openFileDialogue = new OpenFileDialog();
openFileDialog1.DefaultExt = "xml";
openFileDialog1.Filter = "xml files (*.xml)|*.xml";
openFileDialog1.Title = "Select a xml File";
openFileDialog1.ShowDialog();
XDocument xmlFile = XDocument.Load(openFileDialog1.FileName);
**// Remove Declaration**
XDocument doc = new XDocument(new XDeclaration(null, null, null));
**// Add Root Element**
XElement doc1 = XElement.Parse(openFileDialog1.FileName);
XElement root = new XElement("MainInterface", doc1);
//doc.Save(_data)
openFileDialog1.FileName = root.ToString();
-----------------------------------------------------------------------------------
Do something for conversion ~~~
-----------------------------------------------------------------------------------
SaveFileDialog saveFileDialogue1 = new SaveFileDialog();
saveFileDialog1.Filter = "xml File |*.xml";
saveFileDialog1.Title = "Conversion Completed! Save a XML file";
saveFileDialog1.FileName = "XML Converted.xml";
saveFileDialog1.ShowDialog();
xmlFile.Save(saveFileDialog1.FileName);
Should I use XML Writer? Is there simpler way of removing declaration and adding root element on the existing xml file? Thank you in advance.