Search code examples
c#.netxmlxml-serializationxmltextwriter

A few questions about XmlTextWriter


I am new to editing XML and I have a few questions to problems I'm running into.

First: how do I add new lines after each writer.WriteEndElement();. I found examples using writer.WriteWhitespace("\n"); but it doesn't seem to make any new lines.

Second: I think this may not be doing anything because of the previous problem but i wanted to indent my code using this at the end: writer.Formatting = Formatting.Indented;, but it doesn't seem to do anything (most likely because i have no new lines).

Third: Since I'm appending this to a previous file i stripped out the closing tag for my main parent so that i could add this new data. I was hoping i could just have a writer.WriteEndElement(); to close the final tag but since i dont create an opening tag when im writing it doesn't seem to realize that there's an open tag. Is there an good way to do this or should i just end in code to write </closingTagName> at the end of the file.

Any comments or suggestions are appreciated.


Solution

  • Try this:

    using (var stringWriter = new StringWriter())
    using (var writer = new XmlTextWriter(stringWriter))
    {
        writer.WriteRaw("</closingTagName>");
    
        writer.Formatting = Formatting.Indented;
        writer.Indentation = 10;
        writer.WriteStartElement("Element1");
    
        writer.WriteStartElement("Element2");
        writer.WriteString("test");
        writer.WriteEndElement();
    
        writer.WriteEndElement();
    
        writer.WriteWhitespace(Environment.NewLine);
    
        writer.WriteStartElement("Element3");
        writer.WriteEndElement();
    
        var result = stringWriter.ToString();
    

    Result:

    </closingTagName>  -- Closing tag
    <Element1>
              <Element2>test</Element2>  -- Line with the ident 10.
    </Element1>
                  -- extra new line
    <Element3 />