Home > Software design >  How to serialize a class instance to XML in .NET Core?
How to serialize a class instance to XML in .NET Core?

Time:05-04

I am trying to serialize a class instance of the following class into a XML string.

[Serializable]
[XmlRoot]
public class Orders
{
   [XmlElement("Order")]
   public Order order { get; set; }
}

The serializations works fine, but I want to remove the two defaults attributes from the Orders element. Although I need another encoding (ISO-8859-1) and I have to add other attributes to the Orders element.

I wanted to solve the latter by adding a [XmlAttribute] to the Orders class, but it results in the same output.

<?xml version="1.0" encoding="utf-16"?>
<Orders xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
   <Order>
      ...
   <Order>
</Orders>

Does anybody know, how I could achieve that? I highly appreciate any kind of help, cheers! (:


My current root class, which should have a root attribute

public class AGTOSV
{
   private string _attribute = "Hello World";

   [XmlAttribute]
   public string xmlns
   {
       get { return _attribute; }

       set { _attribute = value; }
   }

   // ....

CodePudding user response:

If I understood you correctly, you just want to export plain xml.

Then you need to set XmlWriterSettings as below and tell the serializer to use a empty namespace.

var emptyNamespaces = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });
var settings = new XmlWriterSettings()
{
    OmitXmlDeclaration = true,
};

using (var stream = new StringWriter())
using (var writer = XmlWriter.Create(stream, settings))
{
    var serializer = new XmlSerializer(orders.GetType());
    serializer.Serialize(writer, orders, emptyNamespaces);
    string xml = stream.ToString();
}

Also see How can I make the xmlserializer only serialize plain xml?.

  • Related