Search code examples
c#streamwriter

Is there a way to insert some lines between specific tag in a file


I am trying to insert some lines between a specific location. So, for instance, I wanted to add Test between <ID_1> ... </ID_1>. How is it possible to add it and after I use it I wanted to delete that so that next time when I run I am entering new data. So far I know how can I add but I am entering in the last line of the file.

using (StreamWriter stream = File.AppendText(filename))
{
    stream.WriteLine("line1");
    stream.WriteLine("line2");
    stream.WriteLine("line3");
}

OutputFIle

<ID_1>

</ID_1>

<ID_2>

</ID_2>

<ID_3>

</ID_3>

<ID_4>

</ID_4>

Expected Output

<ID_1>
line1
line2
line3
</ID_1>

<ID_2>

</ID_2>

<ID_3>

</ID_3>

<ID_4>

</ID_4>

Solution

  • Your file is not a valid XML document. It should have a root-tag that encloses all the other tags. I named it root but any other name will do.

    <root>
      <ID_1></ID_1>
      <ID_2></ID_2>
      <ID_3></ID_3>
      <ID_4></ID_4>
    </root>
    

    Then you can do something like this:

    var doc = XDocument.Load(filename);
    doc.Root.Element("ID_1").Value = "line1\r\nline2\r\nline3";
    doc.Save(filename);
    

    It will create a file that looks like this

    <?xml version="1.0" encoding="utf-8"?>
    <root>
      <ID_1>line1
    line2
    line3</ID_1>
      <ID_2></ID_2>
      <ID_3></ID_3>
      <ID_4></ID_4>
    </root>
    

    As you can see, a header line is added that makes it a well-formed XML-file.