3

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.

Alex Aza
  • 76,499
  • 26
  • 155
  • 134
Johnston
  • 2,873
  • 8
  • 29
  • 39
  • 1
    First you shouldn't at all leave a Opening Tag Orphan... Always add complete element With Both opening an closing tag... if you have some Unspecified number of element then just Create Sub Elements for them and add them in the parent Element. – Shekhar_Pro Jun 27 '11 at 04:11
  • i delete it right b4 i start writing to it then i close it again – Johnston Jun 27 '11 at 04:25

1 Answers1

2

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 />
Alex Aza
  • 76,499
  • 26
  • 155
  • 134
  • 1
    @Johnston - what do you mean it didn't work. I tested this code before pasting it here and I pasted the output of `result` string too. – Alex Aza Jun 27 '11 at 04:25
  • 1
    @Johnston - also, I don't recommend using both identation and new lines, as the writer gets confused because of this. Use just identation. – Alex Aza Jun 27 '11 at 04:27
  • hmm removing the formatting code seemed to of fixed it..Thanks! – Johnston Jun 27 '11 at 04:29