How to use XmlWriterSettings() when using override void WriteEndElement()?

前端 未结 5 1657
北恋
北恋 2020-12-11 16:15

I am working with a legacy application that does not import abbreviated empty xml elements. For example:

BAD empty:


G

5条回答
  •  無奈伤痛
    2020-12-11 16:48

    Leaving this here in case someone needs it; since none of the answers above solved it for me, or seemed like overkill.

        FileStream fs = new FileStream("file.xml", FileMode.Create);
        XmlWriterSettings settings = new XmlWriterSettings();
        settings.Indent = true;
        XmlWriter w = XmlWriter.Create(fs, settings);
        w.WriteStartDocument();
        w.WriteStartElement("tag1");
    
            w.WriteStartElement("tag2");
            w.WriteAttributeString("attr1", "val1");
            w.WriteAttributeString("attr2", "val2");
            w.WriteFullEndElement();
    
        w.WriteEndElement();
        w.WriteEndDocument();
        w.Flush();
        fs.Close();
    

    The trick was to set the XmlWriterSettings.Indent = true and add it to the XmlWriter.

    Edit:

    Alternatively you can also use

    w.Formatting = Formatting.Indented;
    

    instead of adding an XmlWriterSettings.

提交回复
热议问题