0

I am trying to add one XElement to an XML file where element is already present in a specific format(see the line 2 where space is present before the Student element), however when i add the Xelement, how could i add a space before the Xelement ? See line 5 in below images for difference of space for formatting ?

Creating the Tag here:

    XElement newStudent = new XElement("Student");
    newStudent.SetAttributeValue("Name", "jhonny");
    newStudent.Add(new XText("\n        "));


    XElement stuSetting = new XElement("Subject");
    stuSetting.SetAttributeValue("Name", "C#");
    stuSetting.SetAttributeValue("Mark", "95");

    newStudent.Add(stuSetting);
    newStudent.Add(new XText("\n  "));

Add in the existing file by loading it using XDocument:

        StudentsXmlFile.Element("Students").Add(newStudent);
        StudentsXmlFile.Element("Students").Add(new XText("\n"));

Required:
enter image description here

Currently Getting output:

enter image description here

usr021986
  • 3,421
  • 14
  • 53
  • 64
  • Do not add you own return '\n'. It is automatically added inside the XDocument. The return is creating the issue with the indenting. – jdweng Nov 20 '20 at 10:48
  • @jdweng: if i dont put \n , it creates the xml element in one line – usr021986 Nov 20 '20 at 18:51
  • You are adding attributes which are always on same line as tag. The code you post and the picture you posted are not consistent. Try SetValue instead of SetAttributeValue. – jdweng Nov 20 '20 at 23:58

0 Answers0