chona
chona

Reputation:

How can I serialize a class with an attribute

I have a class that has

[XmlRoot]
<snip>

[XmlAttribute(AttributeName="x:uid")]
public string uid;

<snip>

It is OK At compile time.. however at runtime, exception occurs at line

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

because of the invalid character in "x:uid".. The element in my class needs to have an "x:uid" attribute for localization purposes.. How can I do that??

Thanks!

Upvotes: 1

Views: 10736

Answers (3)

Igor Brejc
Igor Brejc

Reputation: 19004

As far as I know, you cannot use the namespace prefix in the C# XML attribute declaration. Try just "uid" without "x:"

Upvotes: 0

Greg Beech
Greg Beech

Reputation: 136727

To set the namespace of the attribute, you'll need to use the Namespace property of XmlAttributeAttribute.

If it's particularly important that the prefix used for that namespace is "x" then you can control this using the XmlSerializerNamespaces class when doing serialization, optionally with XmlNamespaceDeclarationsAttribute.


Here's a working example:

[XmlRoot(Namespace = "http://foo")]
public class MyClass
{
    private XmlSerializerNamespaces xmlns;

    [XmlNamespaceDeclarations]
    public XmlSerializerNamespaces Xmlns 
    {
        get
        {
            if (xmlns == null)
            {
                xmlns = new XmlSerializerNamespaces();
                xmlns.Add("x", "http://xxx");
            }
            return xmlns;
        }
        set { xmlns = value; }
    }

    [XmlAttribute("uid", Namespace = "http://xxx")]
    public int Uid { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        var s = new XmlSerializer(typeof(MyClass));
        s.Serialize(Console.Out, new MyClass { Uid = 123 });
        Console.ReadLine();
    }
}

Which produces:

<?xml version="1.0" encoding="ibm850"?>
<MyClass 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
    xmlns:x="http://xxx" 
    x:uid="123" 
    xmlns="http://foo"/>

Upvotes: 9

Marc Gravell
Marc Gravell

Reputation: 1064204

You need to specify the actual namespace - not the alias (which the writer will decide):

[XmlAttribute(AttributeName="uid", Namespace="http://my/full/namespace")]
public string uid;

Note that it is common to use a "const string" for the namespaces, etc. Also, public fields not a good idea - with C# 3.0 you could have (xml attributes not shown):

public string Uid {get;set;}

Upvotes: 5

Related Questions