I haven't tried to use the DataContractSerializer with specialized XML formats, but the XmlSerializer lets you set what is an attribute and what is an element. It is the easiest method as far as I am concerned because you can make a nice object model and use it to read any XML. Here is a PARTIAL example of reading an atom feed. You will need to perform an HttpWebRequest to get the XML (which is pretty straight forward) then use the XmlSerializer to deserialize the feed.
[XmlType(TypeName = "feed", Namespace = "http://www.w3.org/2005/Atom")]
public class Feed
{
[XmlElement(ElementName = "title")]
public string Title { get; set; }
[XmlElement(ElementName = "updated")]
public DateTime? Updated { get; set; }
[XmlElement(ElementName = "id")]
public string Id { get; set; }
[XmlElement(ElementName = "link")]
public Link Link { get; set; }
[XmlElement(ElementName = "entry")]
public List<Entry> Entries { get; set; }
public Feed()
{
Entries = new List<Entry>();
}
}
public class Entry
{
[XmlElement(ElementName = "title")]
public string Title { get; set; }
[XmlElement(ElementName = "updated")]
public DateTime? Updated { get; set; }
[XmlElement(ElementName = "id")]
public string Id { get; set; }
[XmlElement(ElementName = "link")]
public Link Link { get; set; }
[XmlElement(ElementName = "summary")]
public string Summary { get; set; }
}
public class Link
{
[XmlAttribute(AttributeName = "href")]
public string Href { get; set; }
}
Here is a working sample to write/read the feed:
class Program
{
static void Main(string[] args)
{
Feed feed = new Feed();
feed.Title = "Exmple Feed";
feed.Updated = DateTime.Now;
feed.Link = new Link { Href = "http://example.org/" };
feed.Entries.Add(
new Entry
{
Title = "Atom-Powered Robots Run Amok",
Link = new Link { Href = "http://example.org/2003/12/13/atom03" },
Updated = DateTime.Now,
Summary = "Some text."
});
XmlSerializer serializer = new XmlSerializer(typeof(Feed), "http://www.w3.org/2005/Atom");
using (StreamWriter sw = new StreamWriter("c:\\testatom.xml"))
{
serializer.Serialize(sw, feed);
}
using (StreamReader sr = new StreamReader("c:\\testatom.xml"))
{
Feed readFeed = serializer.Deserialize(sr) as Feed;
}
}
}