I have a little problem that perhaps you can help me with.
I try to use the XmlWriter to write an XML-tag that looks like this (w3c feed recommendation):
<atom:link href='http://localhost' rel='self' type='application/rss+xml' />
The problem is that I can’t use the WriteStartElement-method as I would want to (atom as a prefix and link as the element name), since this gives me a ‘ArgumentException: Cannot use a prefix with an empty namespace‘.
My code looks like this:
public void WriteTo(XmlWriter writer, Feed feed) { // RSS element writer.WriteStartElement('rss', ''); writer.WriteAttributeString('version', '2.0'); writer.WriteAttributeString('xmlns', 'atom', string.Empty, 'http://www.w3.org/2005/Atom'); // Channel element writer.WriteStartElement('channel'); // The link to the feed. writer.WriteStartElement('link', 'atom'); writer.WriteAttributeString('href', feed.FeedUrl.ToString()); writer.WriteAttributeString('rel', 'self'); writer.WriteAttributeString('type', 'application/rss+xml'); writer.WriteEndElement(); // Feed information writer.WriteElementString('title', feed.Title); writer.WriteElementString('description', feed.Description); writer.WriteElementString('link', feed.Link.ToString()); // Iterate through all items. foreach (FeedItem item in feed.Items) { writer.WriteStartElement('item'); writer.WriteElementString('title', item.Title); writer.WriteElementString('link', item.Link.ToString()); writer.WriteElementString('description', item.Description); writer.WriteElementString('guid', item.Guid); writer.WriteEndElement(); } // Channel element end writer.WriteEndElement(); // RSS element end writer.WriteEndElement(); }
I assume that my problem is trivial and can easily be solved, but how?
UPDATE:
The problem is solved. Check Jon Skeets answer for the solution.
Why not just use the appropriate namespace (
http://www.w3.org/2005/Atom)?You could write the namespace declaration earlier, in which case you only need the
WriteStartElementoverload which takes the element name and namespace – I think the prefix is then used automatically.