Search code examples
c#xmlwriter

How do I generate the following Xml code in C# with XMLWriterClass?


I'm trying to get this:

      <ATCWaypointEnd id="KLKP">
      </ATCWaypointEnd>

But i get this:

      <ATCWaypointEnd id="KLKP"></ATCWaypointEnd>

Here is my Code:

      writer.WriteStartElement("ATCWaypointEnd");
      writer.WriteStartAttribute("id");
      writer.WriteString(ICAO);
      writer.WriteFullEndElement();

Solution

  • I would recommend creating a class to represent your XML file and then use serialization. That way you can let the framework create the XML elements and you can easily specify whether it should contain line breaks or not (indentation).

    You can also use an external tool to generate your POCO classes, for example: https://xmltocsharp.azurewebsites.net/

    Using the piece of xml you provided:

    // The class representing the XML file
    [XmlRoot(ElementName="ATCWaypointEnd")]
    public class ATCWaypointEnd 
    {
        [XmlAttribute(AttributeName="id")]
        public string Id { get; set; }
    }
    
    // The method that will return the object as a XML string
    public static string GenerateXml(ATCWaypointEnd obj)
    {
        string xml;
        using (var stream = new MemoryStream())
        {
            var serializer = new XmlSerializer(typeof(ATCWaypointEnd));
            
            var writer = new XmlTextWriter(stream, encoding);
            writer.Formatting = Formatting.Indented; // Here
    
            serializer.Serialize(writer, obj);
            xml = encoding.GetString(stream.ToArray());
        }
        return xml;
    }
    

    And then in your code you can use like this:

    var obj = new ATCWaypointEnd();
    obj.Id = "KLKP";
    
    var xml = GenerateXml(obj);