HermanCodes
HermanCodes

Reputation: 99

How to make XML elements self closing with XmlTextWriter

        var fileName = @"C:\Users\MrHer\source\repos\PlaylistGen-main\TestPlaylistGenerator\TestPlaylistGenerator\TestPlaylistGenerator\bin\Debug\netcoreapp3.1\FailedTests.Playlist";
        XmlTextWriter xmlWriter = new XmlTextWriter(fileName, System.Text.Encoding.UTF8);
        xmlWriter.Formatting = System.Xml.Formatting.Indented;
        xmlWriter.WriteStartElement("Playlist");
        xmlWriter.WriteAttributeString("Version", "1.0");

        foreach (var test in failedTestNames)
        {
            xmlWriter.WriteElementString("Add Test", test);
        }

        xmlWriter.WriteEndElement();
        xmlWriter.Flush();
        xmlWriter.Close();

Here is my current code for generating the file I am looking for, current output looks as below -

<Playlist Version="1.0">
  <Add Test>xxxxxxxxxxxxxxxxxxx</Add Test>
  <Add Test>xxxxxxxxxxxxxxxxxxx</Add Test>
</Playlist>

I need to know how I can make the "Add Test" element into a self closing tag so it should look like -

<Playlist Version="1.0">
  <Add Test="xxxxxxxxxxxxxxxxxxx" />
  <Add Test="xxxxxxxxxxxxxxxxxxx" />
</Playlist>

EDIT:

I attempted to use "WriteAttributeString" for the "Add Test" element but this ended up just formatting the "Add Test" elements into the start element of Playlist so it was all just one big line.

Upvotes: 1

Views: 844

Answers (1)

Dmitry Gusarov
Dmitry Gusarov

Reputation: 1639

There reason why you don't have self-closing element, is because you passed "xxx" as a value inside element. Also in your example the element name contains a space, those gives an impression that you becoming closer to the end result. Instead you have to denote start of writing new element "Add", add one attribute named "test" and then close a tag. Writer will decided to close it without text inside (even without empty text) because no value was given to the node and no attempt to write full end been made.

Console.OutputEncoding = Encoding.UTF8;
using var xmlWriter = new XmlTextWriter(Console.OpenStandardOutput(), Encoding.UTF8);
xmlWriter.Formatting = Formatting.Indented;
xmlWriter.WriteStartElement("Playlist");
xmlWriter.WriteAttributeString("Version", "1.0");

foreach (var test in new[] {"abc", "def"})
{
    xmlWriter.WriteStartElement("Add");
    xmlWriter.WriteAttributeString("Test", test);
    xmlWriter.WriteEndElement();
}

xmlWriter.WriteEndElement();

Upvotes: 1

Related Questions