简体   繁体   中英

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();

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);

You can do the following:

writer.WriteStartElement("ATCWaypointEnd");
writer.WriteAttributeString("id", ICAO); 
writer.WriteString(System.Environment.NewLine);
writer.WriteFullEndElement(); 

See below for full code:

Add the following "using" statements:

using System.Xml;
using System.IO;

Option 1:

private void WriteXmlData(string ICAO, string filename)
{

    XmlWriterSettings settings = new XmlWriterSettings();
    settings.Indent = true;
    settings.OmitXmlDeclaration = false;
    settings.NewLineChars = Environment.NewLine;

    string dirName = System.IO.Path.GetDirectoryName(filename);


    if (!System.IO.Directory.Exists(dirName))
    {
        System.Diagnostics.Debug.WriteLine("Output folder doesn't exist. Creating.");

        //create folder if it doesn't exist
        System.IO.Directory.CreateDirectory(dirName);
    }

    using (XmlWriter writer = XmlWriter.Create(filename, settings))
    {
        writer.WriteStartDocument();

        writer.WriteStartElement("ATCWaypointEnd");
        writer.WriteAttributeString("id", ICAO);
        writer.WriteString(System.Environment.NewLine);
        writer.WriteFullEndElement(); 

        writer.WriteEndDocument();

        writer.Close();
        writer.Dispose();
    }

}

Usage:

WriteXmlData("KLKP", @"C:\Temp\test.xml");

Option 2:

private string WriteXmlData(string ICAO)
{
    string xmlOutput = string.Empty;

    XmlWriterSettings settings = new XmlWriterSettings();
    settings.Indent = true;
    settings.OmitXmlDeclaration = false;
    settings.NewLineChars = Environment.NewLine;


    using (MemoryStream ms = new MemoryStream())
    {
        using (XmlWriter writer = XmlWriter.Create(ms, settings))
        {
            writer.WriteStartDocument();

            writer.WriteStartElement("ATCWaypointEnd");
            writer.WriteAttributeString("id", ICAO); 
            writer.WriteString(System.Environment.NewLine);
            writer.WriteFullEndElement(); 

            writer.WriteEndDocument();

            writer.Close();
            writer.Dispose();
        }

        //reset position
        ms.Position = 0;
        using (StreamReader sr = new StreamReader(ms))
        {
            //put XML into string
            xmlOutput = sr.ReadToEnd();

            //clean up
            sr.Close();
            sr.Dispose();
        }

        //clean up
        ms.Close();
        ms.Dispose();
    }

    return xmlOutput;
}

Usage:

string output = WriteXmlData("KLKP");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM