mko
mko

Reputation: 7335

Deserializing XML element containing namespace

I have received an XSD schema, from which I have created object using xsd2code.

The next step was to deserialize sample XML file using the object generated above.

The problem is when I try to deserialize object, there is a problem with namespace of a single element.

I am struggling with this problem for two days now, I would like to find out where to look ie. what could be a problem.

XML successfully deserialized element

<Order xmlns="" id="97440">

but fails to deserialize element when it look like this

<Order xmlns="http://type.domain.com"  id="97440">

What could cause that element Order does not accept any namespace?

If I want to manually edit XML file in VS, and generate a new Order element, it would be generated with empty namespace

c# class contains

[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.0.30319.233")]
    [System.SerializableAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://type.domain.com")]
    [System.Xml.Serialization.XmlRootAttribute(Namespace = "http://type.domain.com", IsNullable = false)]

Upvotes: 1

Views: 1062

Answers (1)

gblmarquez
gblmarquez

Reputation: 527

John,

You'll need something like this in your C# class

[XmlType(AnonymousType = true)]
[XmlRoot(Namespace = "http://type.domain.com")]
public class Order
{
    [XmlAttribute("id")]
    public string Id { get; set; }
    [XmlElement(Namespace ="http://www.cohowinery.com")]
    public decimal Price;  
}

You can set the Namespace for an XmlElement too.

    [XmlElement(Namespace ="http://www.cohowinery.com")]
    public decimal Price;  

Best regards.

Upvotes: 3

Related Questions