Search code examples
c#feedatom-feed

C# XmlReader Colon Issues (Namespace)


I have a strange problem with the XMLReader class. I get atom feed from a URL, and some elements of the xml tree are named like these:

<element:title>Hello World!</element:title>
<element:text>This is just an example</element:text>
<element:id>1</element:id>

Im using

[XmlElement("element:id")]

but this is not working. When I look through the code I see that the reader parse this as

element_x003A_id

but if I use

[XmlElement("element_x003A_id)]

I get nothing. I tried fiddling with the Xml encoding, but the property is read-only. How can I escape this, so I can get the content of the elements (if the element does not have semicolon it works just fine)?


Solution

  • element is a namespace alias. Somewhere, you have (at the top of the file, usually)

    <foo ... xmlns:element="http://something/blah/blog">
    

    the "http://something/blah/blog" is important. Basically, you need:

    [XmlElement("id", Namespace="http://something/blah/blog")]
    public int Id {get;set;}
    

    Or since it is going to be used repeatedly:

    const string MyNamespace = "http://something/blah/blog";
    //...
    [XmlElement("id", Namespace=MyNamespace)]
    public int Id {get;set;}