Search code examples
c#xmldeserializationxml-namespaces

How to deserialize XML element with colon?


i need some help regarding System.XML in C# (.NET).

I have this text somewhere inside an .xml file:

<Location>
    <Longitude>9.118782</Longitude>
    <Latitude>50.178153</Latitude>
    <gml:pos>104049 489104</gml:pos>
</Location>

Since there is a colon in the third field name, i can't use it as a variable. Thus, my class for the deserialization (via XmlSerializer.Deserialize) looks like this:

public class Location
{
    public decimal Longitude { get; set; }      // this works!
    public decimal Latitude { get; set; }       // this works!

    [XmlAttribute("gml:pos")]
    public string GmlPos { get; set; }
}

It throws an exception. I am not very familiar with XML, but due to the exception, i figured out, that the colon stands for a XML-namespace, so i also tried these different options (all at once, of course):

[XmlAttribute("pos", Namespace = "gml")]
public string GmlPos { get; set; }

[XmlAttribute("pos", Namespace = "gml/")]
public string GmlPos { get; set; }

[XmlAttribute(Namespace = "gml")]
public string pos { get; set; }

[XmlAttribute(Namespace = "gml/")]
public string pos { get; set; }

No exception, but the field remains null. I also tried each option with XmlElement instead of XmlAttribute.

Unfortunately this is not easy to google, because the phrase 'namespace' always leads to System.XML...

Please don't suggest changing the .xml file ;)

Thankful for every help, Tim


Solution

  • gml isn't the namespace here - it's a namespace alias. Once you've figured out what the actual namespace is (look for xmlns:gml="..."), you can specify that in XmlAttribute as per your first example. I suspect the namespace is http://www.opengis.net/gml/3.2, in which case you'd have:

    [XmlAttribute("pos", Namespace="http://www.opengis.net/gml/3.2")]
    public string GmlPos { get; set; }