XmlSerializer not creating attribute values

J

John A Grandy

I wrote a simple function to serialize types. I create a simple struct,
marking its public properties with [XmlAttribute]. When I serialize this
struct, none of the properties are present as attributes in the xml stream.


public static string XmlSerialize( object target )
{
XmlSerializer serializer = new XmlSerializer( target.GetType() );
StringBuilder xml = new StringBuilder();
StringWriter writer = new StringWriter( xml );
serializer.Serialize( writer, target );
writer.Close();
return xml.ToString();
}


public struct MyStruct
{

private int? _id;
private string _name;

[XmlAttribute]
public int? Id
{
get { return _id; }
}

[XmlAttribute]
public string Name
{
get { return _name; }
}

public MyStruct( int id, string name )
{
_id = id;
_name = name;
}

}


MyStruct my = new MyStruct( 7, "test" );
string xml = XmlSerialize( my );


OUTPUT :

<?xml version="1.0" encoding="utf-16"?>
<MyStruct xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
 
J

Joern Schou-Rode

public struct MyStruct

1. In order to make the attributes serializable, they must also be
deserializable. Thus you will need to add setters for both properties.

2. I am not sure whether serialization of generic types, such as
Nullable<int> (= int?), is supported by the XmlSerializer. If you still
face problems after adding the setters, try to change the type of the Id
parameter to a plain int.
 
A

Arne Vajhøj

John said:
I wrote a simple function to serialize types. I create a simple struct,
marking its public properties with [XmlAttribute]. When I serialize this
struct, none of the properties are present as attributes in the xml stream.
public struct MyStruct
{

private int? _id;
private string _name;

[XmlAttribute]
public int? Id
{
get { return _id; }
}

[XmlAttribute]
public string Name
{
get { return _name; }
}

public MyStruct( int id, string name )
{
_id = id;
_name = name;
}

}

You will need set implemente din both properties.

And you will need to either use int instead of int? or
use an element instead of an attribute (attributes can not
be nullable).

Arne
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top