Search code examples
c#xmlnsxmlelement

Sitemap image element


i have a class for build xml sitemap in c# , i use it in a mvc controller to generate sitemap :

public class Location
    {
        public enum eChangeFrequency
        {
            always,
            hourly,
            daily,
            weekly,
            monthly,
            yearly,
            never
        }

        [XmlElement("loc")]
        public string Url { get; set; }

        [XmlElement("changefreq")]
        public eChangeFrequency? ChangeFrequency { get; set; }
        public bool ShouldSerializeChangeFrequency() { return ChangeFrequency.HasValue; }

        [XmlElement("lastmod")]
        public DateTime? LastModified { get; set; }
        public bool ShouldSerializeLastModified() { return LastModified.HasValue; }

        [XmlElement("priority")]
        public double? Priority { get; set; }
        public bool ShouldSerializePriority() { return Priority.HasValue; }

        [XmlElement("image")]
        public Image Image { get; set; }
    }

    [XmlType("image")]
    public class Image
    {
        [XmlElement(ElementName = "loc")]
        public string UrlLocation { get; set; }

        [XmlElement(ElementName = "caption")]
        public string Caption { get; set; }

        [XmlElement(ElementName = "title")]
        public string Title { get; set; }

    }

this is output , when i use it :

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

but i want correct format , like this :

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

i want to add this prefix to image element , thanks for your help


Solution

  • Read this page https://msdn.microsoft.com/tr-tr/library/system.xml.serialization.xmlnamespacedeclarationsattribute(v=vs.110).aspx
    There is good example.
    You should add XmlSerializerNamespaces type property in your Image class and you should add string prefix and string namespace values.

    I read this XML Serialization and namespace prefixes .

    [XmlType("image", Namespace = "http://flibble")]
    public class Image
    {
        [XmlElement(ElementName = "loc")]
        public string UrlLocation { get; set; }
    
        [XmlElement(ElementName = "caption")]        
        public string Caption { get; set; }
    
        [XmlElement(ElementName = "title")]
        public string Title { get; set; }
    
    }  
    

    Usage must be as below.

    Image mySelect = new Image();
            mySelect.Caption = "Caption";
            mySelect.Title = "Title";
            mySelect.UrlLocation = "www";
    
            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
            ns.Add("image", "http://flibble");
            XmlSerializer ser = new XmlSerializer(typeof(Image));
    
            ser.Serialize(Console.Out, mySelect,ns);