所以我仍然在问这个话题:-(
所以我创建了一个对象,用Xml序列化属性来装饰它,从我看到的我添加一个空的命名空间到xml序列化namepsace集合,以便不获取我不想要的多余属性.
编辑:我的意思是这些属性:
所以它给了我两个额外的属性.
经过进一步调查,如果我改变文件的开头:**
writer.WriteStartElement("urlset","http://www.sitemaps.org/schemas/sitemap/0.9");
至
writer.WriteStartElement("urlset");
**然后我没有在url标签中获得空的xmlns =""属性.这很好但是我确实需要根元素xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
,即:
但我仍然xmlns=""
在序列化类型中获得一个空属性.
[XmlRoot(ElementName = "url", Namespace="")] public class SitemapNode { [XmlElement(ElementName = "loc")] public string Location { get; set; } [XmlElement(ElementName = "lastmod")] public DateTime LastModified { get; set; } [XmlElement(ElementName = "changefreq")] public SitemapChangeFrequency ChangeFrequency { get; set; } [XmlElement(ElementName = "priority")] public decimal Priority { get; set; } public SitemapNode() { Location = String.Empty; LastModified = DateTime.Now; ChangeFrequency = SitemapChangeFrequency.monthly; Priority = 0.5M; } public SitemapNode(string location, DateTime lastModified, SitemapChangeFrequency changeFrequency, decimal priority) { Location = location; LastModified = lastModified; ChangeFrequency = changeFrequency; Priority = priority; } }
然后我使用以下内容附加到我的XmlWriter:
foreach (uk.co.andrewrea.SitemapNode node in List) { XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); ns.Add(String.Empty, String.Empty); Serializer.Serialize(Writer, node, ns); }
这很好,除了我留下像这样的emtpy xmlns =""
任何想法?我可以使用XmlTextWriter和XmlDocument实现这一点,但我需要使用XmlWriter来实现它.
任何帮助是极大的赞赏.
这工作(您只需要它们在同一名称空间中,并使用名称空间类,因此写入程序不会混淆):
[TestMethod] public void TestMethod3() { var list = new []{new SitemapNode("1", DateTime.Now, 1), new SitemapNode("2", DateTime.Now.AddDays(1), 2)}; var serializer = new XmlSerializer(typeof(SitemapNode)); var st = new MemoryStream(); using (var writer = XmlWriter.Create(st)) { var ns = new XmlSerializerNamespaces(); ns.Add("", "test"); writer.WriteStartElement("test", "test"); foreach (SitemapNode node in list) { serializer.Serialize(writer, node, ns); } writer.WriteEndElement(); } st.Position = 0; TestContext.WriteLine(new StreamReader(st).ReadToEnd()); } [XmlRoot(ElementName = "url", Namespace = "test")] public class SitemapNode { [XmlElement(ElementName = "loc")] public string Location { get; set; } [XmlElement(ElementName = "lastmod")] public DateTime LastModified { get; set; } [XmlElement(ElementName = "priority")] public decimal Priority { get; set; } public SitemapNode() { Location = String.Empty; LastModified = DateTime.Now; Priority = 0.5M; } public SitemapNode(string location, DateTime lastModified, decimal priority) { Location = location; LastModified = lastModified; Priority = priority; } }
输出是(基于您的评论,你正在寻找):
1 2009-03-05T13:35:54.6468-07:00 1 2 2009-03-06T13:35:54.6478-07:00 2