Search code examples
c#xmlxmlwriter

XmlWriter <image:image>


Apologies if this is obvious but I am trying to write some xml for a sitemap like this:

<url>
    <loc>http://...</loc>
    <priority>0.5</priority>
    <image:image>
      <image:loc>http://...</image:loc>
     </image:image>
</url>

With the following code:

    const string locationPrefix = "loc";
    const string imagePrefix = "image";
    writer.WriteStartElement("image", imagePrefix);
    writer.WriteStartElement("image", locationPrefix);
    writer.WriteValue(imageUrl);
    writer.WriteEndElement(); // </image:loc>
    writer.WriteEndElement(); // </image:image>

But am getting this instead.

<image xmlns="image">
   <image xmlns="loc">http://...</image>
 </image>

Could someone tell me where I am going wrong here?

Edit: this did it

writer.WriteStartElement("image", imagePrefix, null);

Solution

  • Use the overload of WriteStartElement with 3 parameters http://msdn.microsoft.com/en-us/library/7cdfkth5.aspx

    1. prefix : The namespace prefix of the element.
    2. localName : The local name of the element.
    3. ns : The namespace URI to associate with the element.