2

Please i'm trying to insert data into xml, this is the current format of my xml file after inserting data

<?xml version="1.0" encoding="utf-8"?>
<ApplicationData>
        <Minutes>

        </Minutes>

        <Minute MinuteId="6" Title="Project6" Date="6" Time="Project6" Location="6" MinuteDocumentFile="Project6" />
        <Minute MinuteId="6" Title="Project6" Date="6" Time="Project6" Location="6" MinuteDocumentFile="Project6" /> 

</ApplicationData>

using this code below

XmlTextReader _xmlTextReader = new XmlTextReader(config.XMLPath);
                XmlDocument _xmlDocument = new XmlDocument();
                _xmlDocument.Load(_xmlTextReader);
                //Note: Close the reader object to release the xml file. Else while saving you will get an error that it is 
                //being used by another process.
                _xmlTextReader.Close();

                XmlElement _minutesElement = _xmlDocument.CreateElement("Minute");
                _minutesElement.SetAttribute("MinuteId", "6");
                _minutesElement.SetAttribute("Title", "Project6");
                _minutesElement.SetAttribute("Date", "6");
                _minutesElement.SetAttribute("Time", "Project6");
                _minutesElement.SetAttribute("Location", "6");
                _minutesElement.SetAttribute("MinuteDocumentFile", "Project6");

                _xmlDocument.DocumentElement.AppendChild(_minutesElement);
                _xmlDocument.Save(config.XMLPath);

That above code works fine, but my challenge now is, i'm trying to achieve the current format of xml shown below

<?xml version="1.0" encoding="utf-8"?>
<ApplicationData>
        <Minutes>
             <Minute MinuteId="6" Title="Project6" Date="6" Time="Project6" Location="6" MinuteDocumentFile="Project6" />
             <Minute MinuteId="6" Title="Project6" Date="6" Time="Project6" Location="6" MinuteDocumentFile="Project6" /> 
        </Minutes>
</ApplicationData>

I want to store the created "Minute" XmlElement inside the "Minutes" Element, not outside it.

Thanks..

MIcheal David
  • 149
  • 1
  • 4
  • 18

2 Answers2

1

The line

_xmlDocument.DocumentElement.AppendChild(_minutesElement);

is just appending your new _minutesElement to the end of the tree. You need to tell it which element you want it to belong to.

Changing it instead to be:

_xmlDocument.DocumentElement["Minutes"].AppendChild(_minutesElement);

Gives:

<?xml version="1.0" encoding="utf-8"?>
<ApplicationData>
  <Minutes>
    <Minute MinuteId="6" Title="Project6" Date="6" Time="Project6" Location="6" MinuteDocumentFile="Project6" />
  </Minutes>
</ApplicationData>
danielmcn
  • 390
  • 6
  • 15
1
var doc = XElement.Load(config.XMLPath);
var target = doc.Descendants("Minutes").First();
target.Add(new XElement("Minute", new XAttribute("MinuteId", 6), new ...));
doc.Save(config.XMLPath);
H H
  • 263,252
  • 30
  • 330
  • 514