22

我想使用 XmlSerializer 生成以下内容:

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

所以我尝试向我的元素添加一个命名空间:

[...]

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

[...]

但输出是:

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

那么生成前缀标签的正确方法是什么?

4

2 回答 2

45

首先,atom 命名空间通常是这样的:

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

为了让你的标签使用atom命名空间前缀,你需要用它来标记你的属性:

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

您还需要告诉XmlSerializer使用它(感谢@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);
于 2010-05-11T12:32:01.700 回答
0

看看Xml 序列化和命名空间前缀

于 2010-05-11T12:23:14.517 回答