0

I am trying to create an XML file of the form:

<NodeTag>
  <Tag1>tag 1 data</Tag1>
  <Tag2></Tag2>  
</NodeTag>

Using a standard XmlWriter like this:

XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = Encoding.Unicode;
settings.CloseOutput = true;
settings.Indent = true;
settings.NewLineOnAttributes = false;
XmlWriter writer = XmlWriter.Create(xmlFilePath, settings);

myXmlDoc.save(writer)

I get output that looks like this:

<NodeTag>
  <Tag1>tag 1 data</Tag1>
  <Tag2 />  
</NodeTag>

I cannot find any settings in XmlWriterSettings that control whether full elements are written or not.

I have tried creating a class to write full elements out by overridding WriteEndElement():

class XmlFullElementTextWriter : XmlTextWriter
{
    public XmlFullElementTextWriter(TextWriter tw) : base(tw) { }
    public XmlFullElementTextWriter(Stream s, Encoding e) : base(s, e) { }
    public XmlFullElementTextWriter(String s, Encoding e) : base(s, e) { }

    public override void WriteEndElement()
    {
        base.WriteFullEndElement();
    }
}

which I call like this:

XmlFullElementTextWriter writer = new XmlFullElementTextWriter(xmlFilePath, Encoding.Unicode);
writer.Formatting = Formatting.Indented;
myXmlDoc.save(writer);

which gives me this:

<NodeTag>
  <Tag1>tag 1 data</Tag1>
  <Tag2>
  </Tag2>  
</NodeTag>

I know that the different forms are equivalent, but I need them this way.

Note -- I am using Visual Studio 2012 running on .NET Framework 4.5.50709

Jay Elston
  • 1,978
  • 1
  • 19
  • 38
  • @Zong -- Thanks, I missed that question when I searched for pre-existing questions. Unfortuantely its answers are of no help. At any rate, I do not think this is a duplicate. That question asked how to force close tags from XmlWriter. I am trying to force this behavior from XmlDocument's save() method. I did find a way to force the explicit close tag (by overriding XmtTextWriter), but I still have a extra line feed that I want to get rid of. – Jay Elston Oct 21 '13 at 21:54
  • It is very close to this question: http://stackoverflow.com/questions/13389960/how-to-use-xmlwritersettings-when-using-override-void-writeendelement which also has an answer (use the XmlWrappingWriter) that worked for me. So, if you want, close this as a duplicate. – Jay Elston Oct 21 '13 at 22:39

0 Answers0