简体   繁体   中英

Flattening Serialized XML in C#

If I have an object :-

class c { List<b> b; }

class b { string a; }

When c is converted to XML, the resultant is :-

<c> <b> <b> <a>Hello</a> </b>...

Is there any way I can flatten the XML either through code structure or options so that I can get rid of one of the layers? I ultimately want the XML to be just :-

<c> <b> <a>Hello</a> </b>....

Or another way to look at the problem, how can deserialize :-

<c><b><a>Name</a></b><b><a>Age</a></b></c>

to a C# class structure?

Thanks in advance? If not possible, let me know please.

One option is to implement IXmlSerializable to gain full control over exactly what form the XML serialisation for your class should take.

Alternatively, you may be able to get away with decorating your classes and properties with attributes that control XML serialisation .

If this is what you want:

<ArrayOfB>
     <b>
          <a>Name</a>
     </b>
     <b>
          <a>Age</a>
     </b>
</ArrayOfB>

Then this should work.

public class XMLPlayground
{
    public void Play()
    {
        List<b> list = new List<b>()
        {    
            new b() {a = "Name"}, 
            new b() {a = "Age"}, 
        };
        string str = SerializeToString(list);
        Console.WriteLine(str); 
    }

    private string SerializeToString(object o)
    {
        if (o == null) return "";
        var xs = new XmlSerializer(o.GetType());

        XmlSerializerNamespaces tellTheSeriliserToIgnoreNameSpaces = new XmlSerializerNamespaces();
        tellTheSeriliserToIgnoreNameSpaces.Add(String.Empty, String.Empty);
        XmlWriterSettings tellTheWriterToOmitTheXmlDeclaration = new XmlWriterSettings { OmitXmlDeclaration = true };

        using (StringWriter writer = new StringWriter())
        {
            using (var xw = XmlWriter.Create(writer, tellTheWriterToOmitTheXmlDeclaration))
            {
                xs.Serialize(xw, o, tellTheSeriliserToIgnoreNameSpaces);
                return writer.ToString();
            }
        }
    }
}

[Serializable]
public class b
{
    public string a { get; set; }
}

Here's some insight on what you want to achieve, but to me the solution looks rather esoteric. You may wanna try SAX approach with XmlTextReader and construct your object on the fly.

C# Xml serialization, collection and root element

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