问题
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