0
votes

I have some xml and need to deserialize it into an C# object but I can't figure out how to get the value from the xlink:href. The exception I get is

Invalid name character in 'xlink:href'.

But when I change the XmlAttribute value to href or xlink there is no value set. How can I get this value with the XmlSerializer?

XML example:

<result xmlns:xlink="http://www.w3.org/1999/xlink">
    <items country="nl">
       <item name="cube" xlink:href="http://url"/>
       <item name="square"  xlink:href="http://url"/>
    </items>
</result>

C# Class:

[XmlRoot("result")]
public class Result
{
    [XmlArray("items")]
    [XmlArrayItem("item")]
    public List<Item> Items { get; set; }
}

public class Item
{
    [XmlAttribute("name")]
    public string Name { get; set; }

    [XmlAttribute("xlink:href")]
    public string Url { get; set; }
}

Deserialize code:

Stream response = GetResponseFromRequest(requestUrl);
var serializer = new XmlSerializer(typeof(Result));
Result result = (Result)serializer.Deserialize(response);
1
You need to consider the namespace: [XmlAttribute("href", Namespace = "http://www.w3.org/1999/xlink")] and use XmlSerializerNamespaces to map the prefix. See stackoverflow.com/a/20681227/3190413 - helderdarocha

1 Answers

1
votes

Add the namespace to the XmlAttribute attribute:

public class Item
{
    [XmlAttribute("name")]
    public string Name { get; set; }

    [XmlAttribute("href", Namespace="http://www.w3.org/1999/xlink")]
    public string Url { get; set; }
}