Search code examples
c#linqserializationxsi

How Can I add an XSI type to an element that is being serialized using LINQ


I want to serialize an Object of a Type of a particular class and containing a particular XSI Type

Can I Do this in LINQ ?


Solution

  • To get the following XML:

    <Model xsi:type="SettingsModel" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <Name>Test05</Name>
      <IsActive>false</IsActive>
      <IsHidden>false</IsHidden>
    </Model>
    

    You can use the following code:

    var model = new { Name = "Test05", IsActive = false, IsHidden = false };
    
    var namespaceName = "http://www.w3.org/2001/XMLSchema-instance";
    XNamespace xsi = XNamespace.Get(namespaceName);
    var x = new XElement("Model",
        new XAttribute(xsi + "type", "SettingsModel"),
        new XAttribute(XNamespace.Xmlns + "xsi", namespaceName),
        new XElement("Name", model.Name),
        new XElement("IsActive", model.IsActive),
        new XElement("IsHidden", model.IsHidden)
        );
    
    Console.WriteLine(x);
    

    LINQ to XML is an exercise in frustration. In the long term you may prefer to use concrete classes with appropriate XML serialization decorators.

    === edit ===

    Here is some additional code that writes the data to an XML file:

    var settings = new XmlWriterSettings()
    {
        Indent = true,
        OmitXmlDeclaration = true
    };
    using (var stream = new FileStream("Test05.xml", FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))
    using (var writer = XmlWriter.Create(stream, settings))
    {
        x.WriteTo(writer);
    }