Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize a C# class to XML with attributes and a single value for the class

I am using C# and XmlSerializer to serialize the following class:

public class Title {     [XmlAttribute("id")]     public int Id { get; set; }      public string Value { get; set; } } 

I would like this to serialize to the following XML format:

<Title id="123">Some Title Value</Title> 

In other words, I would like the Value property to be the value of the Title element in the XML file. I can't seem to find any way to do this without implementing my own XML serializer, which I would like to avoid. Any help would be appreciated.

like image 725
J Kerchner Avatar asked Feb 29 '12 17:02

J Kerchner


People also ask

What is serialization C?

Serialization in C# is the process of converting an object into a stream of bytes to store the object to memory, a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called deserialization.

What it means to serialize?

Serialization is the process of converting a data object—a combination of code and data represented within a region of data storage—into a series of bytes that saves the state of the object in an easily transmittable form.

What is the use of serialize ()?

The serialize() function converts a storable representation of a value. To serialize data means to convert a value to a sequence of bits, so that it can be stored in a file, a memory buffer, or transmitted across a network.

How do I make my AC class serializable?

The easiest way to make a class serializable is to mark it with the SerializableAttribute as follows. The following code example shows how an instance of this class can be serialized to a file. MyObject obj = new MyObject(); obj. n1 = 1; obj.


1 Answers

Try using [XmlText]:

public class Title {   [XmlAttribute("id")]   public int Id { get; set; }    [XmlText]   public string Value { get; set; } } 

Here's what I get (but I didn't spend a lot of time tweaking the XmlWriter, so you get a bunch of noise in the way of namespaces, etc.:

<?xml version="1.0" encoding="utf-16"?> <Title xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"        xmlns:xsd="http://www.w3.org/2001/XMLSchema"        id="123"        >Grand Poobah</Title> 
like image 151
Nicholas Carey Avatar answered Sep 22 '22 04:09

Nicholas Carey