开发者

Serialize into an XML Fragment - not XML Document

开发者 https://www.devze.com 2022-12-28 22:47 出处:网络
How do I serialize an XML-serializable object to an XML fragment (no XML declaration nor namespace references 开发者_JAVA百科in the root element)?Here is a hack-ish way to do it without having to load

How do I serialize an XML-serializable object to an XML fragment (no XML declaration nor namespace references 开发者_JAVA百科in the root element)?


Here is a hack-ish way to do it without having to load the entire output string into an XmlDocument:

using System;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

public class Example
{
    public String Name { get; set; }

    static void Main()
    {
        Example example = new Example { Name = "Foo" };

        XmlSerializer serializer = new XmlSerializer(typeof(Example));

        XmlSerializerNamespaces emptyNamespace = new XmlSerializerNamespaces();
        emptyNamespace.Add(String.Empty, String.Empty);

        StringBuilder output = new StringBuilder();

        XmlWriter writer = XmlWriter.Create(output,
            new XmlWriterSettings { OmitXmlDeclaration = true });
        serializer.Serialize(writer, example, emptyNamespace);

        Console.WriteLine(output.ToString());
    }
}


You should be able to just serialize like you usually do, and then use the Root property from the resulting document.

You may need to clear the attributes of the element first.


By the way this is awesome. I implemented this code to make it easy to work with xml fragments as classes quickly and then you can just replace the node when finished. This makes the transition between code and xml ultra-easy.

First create some extension methods.

public static class SerializableFragmentExtensions
{
    public static XElement ToElement(this ISerializableFragment iSerializableFragment)
    {
        var serializer = new XmlSerializer(iSerializableFragment.GetType());
        var emptyNamespace = new XmlSerializerNamespaces();
        emptyNamespace.Add(String.Empty, String.Empty);

        var output = new StringBuilder();

        var writer = XmlWriter.Create(output,
            new XmlWriterSettings { OmitXmlDeclaration = true });
        serializer.Serialize(writer, iSerializableFragment, emptyNamespace);
        return XElement.Parse(output.ToString(), LoadOptions.None);
    }
    public static T ToObject<T>(this XElement xElement)
    {
        var serializer = new XmlSerializer(typeof (T));
        var reader = xElement.CreateReader();
        var obj = (T) serializer.Deserialize(reader);
        return obj;
    }
}

Next Implement the required interface (marker interface--I know you are not supposed to but I think this is the perfect reason to it.)

public interface ISerializableFragment
{
}

Now all you have to do is decorate any Serializable class, you want to convert to an XElement Fragment, with the interface.

[Serializable]
public class SomeSerializableClass : ISerializableFragment
{
    [XmlAttribute]
    public string SomeData { get; set; }
}

Finally test the code.

    static void Main(string[] args)
    {
        var someSerializableClassObj = new SomeSerializableClass() {SomeData = "Testing"};
        var element = someSerializableClass.ToElement();
        var backToSomeSerializableClassObj = element.ToObject<SomeSerializableClass>();
    }

Thanks again for this amazingly useful code.

0

精彩评论

暂无评论...
验证码 换一张
取 消