Question

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);
Was it helpful?

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.

OTHER TIPS

You want to add prefix to your xml elements which should point to a namespace. Try this

using(var ms = new MemoryStream())
using (var writer = XmlWriter.Create(ms))
{
    const string imagePrefix = "img";
    writer.WriteStartElement(imagePrefix, "image", "http://image.com");
    writer.WriteStartElement(imagePrefix, "local", "http://image.com");
    writer.Flush();
    writer.Close();
    Console.WriteLine(Encoding.UTF8.GetString(ms.ToArray()));
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top