Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XML Serialization question - How to Serialize Element, Attribute and Text from One Object

I'm new into XML Serialization using .NET and after working with it for some time I'm quite fuzzled now. I can serialize elements with attributes containing other elements but how can I serialize something like

<myElement name="foo">bar</myElement> 

I use a class for myElement with a XmlAttribute for the "name", but how to refer the value of the XML Element?

Thanks in advance.

like image 414
Haiko Wick Avatar asked Apr 28 '09 09:04

Haiko Wick


People also ask

What is the correct way of using XML serialization?

XML Serialization Considerations Type identity and assembly information are not included. Only public properties and fields can be serialized. Properties must have public accessors (get and set methods). If you must serialize non-public data, use the DataContractSerializer class rather than XML serialization.

What is the difference between binary serialization and XML serialization?

Xml Serializer serializes only public member of object but Binary Serializer serializes all member whether public or private. In Xml Serialization, some of object state is only saved but in Binary Serialization, entire object state is saved.

Which class should be used to serialize an object in XML format?

Xml. Serialization namespace) class is used to serialize and deserialize. The class method Serialize is called. Since we have to serialize in a file, we create a " TextWriter ".


1 Answers

[XmlText], like so:

using System; using System.Xml.Serialization; [Serializable, XmlRoot("myElement")] public class MyType {     [XmlAttribute("name")]     public string Name {get;set;}      [XmlText]     public string Text {get;set;} }  static class Program {     static void Main() {         new XmlSerializer(typeof(MyType)).Serialize(Console.Out,             new MyType { Name = "foo", Text = "bar" });     } } 
like image 50
Marc Gravell Avatar answered Oct 12 '22 01:10

Marc Gravell