C# 如何使用XmlSerializer生成标记前缀
我想使用XmlSerializer生成以下内容:C# 如何使用XmlSerializer生成标记前缀,c#,xmlserializer,C#,Xmlserializer,我想使用XmlSerializer生成以下内容: <atom:link href="http://dallas.example.com/rss.xml" rel="self" type="application/rss+xml" /> 但结果是: <link xmlns="atom" href="http://dallas.example.com/rss.xml" rel="self" type="application/rss+xml" /> 那么,生成前缀标记
<atom:link href="http://dallas.example.com/rss.xml" rel="self" type="application/rss+xml" />
但结果是:
<link xmlns="atom" href="http://dallas.example.com/rss.xml" rel="self" type="application/rss+xml" />
那么,生成前缀标记的正确方法是什么呢?首先看一看,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=newxmlserializernamespaces();ns.Add(“atom”,”;serializer.Serialize(xmlWriter,_rss,ns);它只是将xmlns:atom=”“作为属性添加到我的根元素中……但如果我使用=>新的xmlsyndictioncontent(contentType,content,serializerXml),则不会将前缀添加到我的tagHi中;其中我无法建立名称空间。我能做什么?我希望atom条目的内容与名称空间保持一致:(
[XmlElement("link", Namespace="http://www.w3.org/2005/Atom")]
public AtomLink AtomLink { get; set; }
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);