C# 在xml序列化对象中添加前缀

C# 在xml序列化对象中添加前缀,c#,xml,asp.net-mvc,serialization,C#,Xml,Asp.net Mvc,Serialization,我是XML新手我想要这种类型的输出: <?xml version="1.0" encoding="utf-8"?> <urlset xmlns:video="http://www.google.com/schemas/sitemap-video/1.1" xmlns:image="http://www.google.com/schemas/sitemap-image/1.1" xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"

我是XML新手我想要这种类型的输出:

<?xml version="1.0" encoding="utf-8"?>
<urlset xmlns:video="http://www.google.com/schemas/sitemap-video/1.1" xmlns:image="http://www.google.com/schemas/sitemap-image/1.1" xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <url>
    <loc>http://example.com/sample.html</loc>;
    <image:image>
    <image:loc>http://example.com/image.jpg</image:loc>;
    </image:image>
    <image:image>
    <image:loc>http://example.com/photo.jpg</image:loc>;
    </image:image>
    </url>
</urlset>
使用这个,我得到了这种类型的输出

<?xml version="1.0" encoding="utf-8"?>
<urlset xmlns:video="http://www.google.com/schemas/sitemap-video/1.1" xmlns:image="http://www.google.com/schemas/sitemap-image/1.1" xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <url>
    <loc>http://example.com/sample.html</loc>

    <image>
      <loc>http://example.com/image.jpg/</loc>

    </image>
  </url>

http://example.com/sample.html
http://example.com/image.jpg/

那么如何在图像标签中添加前缀图像

将与
“image”
前缀对应的名称空间添加到
ImageList
属性所附加的属性中:

    [XmlElement(ElementName = "image", Namespace = "http://www.google.com/schemas/sitemap-image/1.1")]
    public List<Image> ImageList { get; set; }
[xmlement(ElementName=“image”,命名空间=”http://www.google.com/schemas/sitemap-image/1.1")]
公共列表ImageList{get;set;}
这样做将设置为类序列化时产生的XML元素指定的名称空间。因为您映射了命名空间
“http://www.google.com/schemas/sitemap-image/1.1“
图像:”
在序列化过程中,将显示前缀


要进一步阅读,请参见

太好了,这是我见过的最好的答案。
var path = HttpContext.Current.Server.MapPath("sitemap.xml");
                XmlTextReader textReader = new XmlTextReader(path);
                System.Xml.Serialization.XmlSerializer writer =
                 new System.Xml.Serialization.XmlSerializer(typeof(Sitemap));
                XmlSerializerNamespaces nameSpace = new XmlSerializerNamespaces();
                nameSpace.Add("image", "http://www.google.com/schemas/sitemap-image/1.1");

                nameSpace.Add("video", "http://www.google.com/schemas/sitemap-video/1.1");

                System.IO.StreamWriter file = new System.IO.StreamWriter(path);


                writer.Serialize(file, sitemap, nameSpace);


                file.Close();
<?xml version="1.0" encoding="utf-8"?>
<urlset xmlns:video="http://www.google.com/schemas/sitemap-video/1.1" xmlns:image="http://www.google.com/schemas/sitemap-image/1.1" xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <url>
    <loc>http://example.com/sample.html</loc>

    <image>
      <loc>http://example.com/image.jpg/</loc>

    </image>
  </url>
    [XmlElement(ElementName = "image", Namespace = "http://www.google.com/schemas/sitemap-image/1.1")]
    public List<Image> ImageList { get; set; }