views:

337

answers:

3

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!

A: 

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

Igor Brejc
XML attributes *can* have namespaces.
Greg Beech
Yes, you're right... my mistake
Igor Brejc
+3  A: 

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"/&gt;
Greg Beech
+2  A: 

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;}
Marc Gravell