How to generate tag prefixes using XmlSerializer

为君一笑 提交于 2019-12-23 06:51:21

问题


I wanted to generate the following using XmlSerializer :

<atom:link href="http://dallas.example.com/rss.xml" rel="self" type="application/rss+xml" />

So I tried to add a Namespace to my element :

[...]

    [XmlElement("link", Namespace="atom")]
    public AtomLink AtomLink { get; set; }

[...]

But the output is :

<link xmlns="atom" href="http://dallas.example.com/rss.xml" rel="self" type="application/rss+xml" />

So what is the correct way to generate prefixed tags ?


回答1:


First off, the atom namespace is normally this:

xmlns:atom="http://www.w3.org/2005/Atom"

In order to get your tags to use the atom namespace prefix, you need to mark your properties with it:

[XmlElement("link", Namespace="http://www.w3.org/2005/Atom")]
public AtomLink AtomLink { get; set; }

You also need tell the XmlSerializer to use it (thanks to @Marc Gravell):

XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("atom", "http://www.w3.org/2005/Atom");
XmlSerializer xser = new XmlSerializer(typeof(MyType));
xser.Serialize(Console.Out, new MyType(), ns);



回答2:


Take a look at Xml Serialization and namespace prefixes



来源:https://stackoverflow.com/questions/2810548/how-to-generate-tag-prefixes-using-xmlserializer

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!