XML序列化后去掉空的xmlns=""所以我还在问这个话题:-(属性来装饰一下,我看到的我加xml序列化namepsace集合的空命名空间,以免获得我不打算拥有的冗余属性。编辑:我的意思是这些属性:所以它给了我两个额外的属性。经过进一步调查,如果我改变了开头文件:**writer.WriteStartElement("urlset","http://www.sitemaps.org/schemas/sitemap/0.9");towriter.WriteStartElement("urlset");**然后我不明白url标记中的空xmlns=""属性。这很好,但我确实需要根元素具有xmlns="http://www.sitemaps.org/schemas/sitemap/0.9",即:但我仍然得到序列化类型中的空xmlns=""属性。[XmlRoot(ElementName="url",Namespace="")]publicclassSitemapNode{[XmlElement(ElementName="loc")]publicstringLocation{get;放;}[XmlElement(ElementName="lastmod")]publicDateTimeLastModified{get;放;}[XmlElement(ElementName="changefreq")]publicSitemapChangeFrequencyChangeFrequency{get;放;}[XmlElement(ElementName="priority")]publicdecimalPriority{get;放;}publicSitemapNode(){Location=String.Empty;LastModified=DateTime.Now;ChangeFrequency=SitemapChangeFrequency.monthly;优先级=0.5M;}publicSitemapNode(stringlocation,DateTimelastModified,SitemapChangeFrequencychangeFrequency,decimalpriority){Location=location;LastModified=lastModified;变化频率=变化频率;优先级=优先级;}}然后我使用以下内容添加到我的XmlWriter:foreach(uk.co.andrewrea.SitemapNodenodeinList){ns.Add(String.Empty,String.Empty);系列lizer.Serialize(Writer,node,ns);这工作正常,除了我留下像这样的emtpyxmlns=""有什么想法吗?同样,我可以使用XmlTextWriter和XmlDocument来实现这一点,但我需要使用XmlWriter来实现。非常感谢任何帮助。这是有效的(你只需要它们在同一个命名空间中,并且你使用命名空间类,这样作者就不会感到困惑):[TestMethod]publicvoidTestMethod3(){varlist=new[]{newSitemapNode("1",DateTime.Now,1),newSitemapNode("2",DateTime.Now.AddDays(1),2)};varserializer=newXmlSerializer(typeof(SitemapNode));varst=newMemoryStream();使用(varwriter=XmlWriter.Create(st)){varns=newXmlSerializerNamespaces();ns.Add("","测试");writer.WriteStartElement("测试","测试");foreach(列表中的SitemapNode节点){serializer.Serialize(writer,node,ns);}writer.WriteEndElement();}st.Position=0;TestContext.WriteLine(新的StreamReader(st).ReadToEnd());}[XmlRoot(ElementName="url",Namespace="test")]publicclassSitemapNode{[XmlElement(ElementName="loc")]publicstringLocation{get;放;}[XmlElement(ElementName="lastmod")]publicDateTimeLastModified{get;放;}[XmlElement(ElementName="priority")]publicdecimalPriority{get;放;}publicSitemapNode(){Location=St戒指.空;LastModified=DateTime.Now;优先级=0.5M;}publicSitemapNode(stringlocation,DateTimelastModified,decimalpriority){Location=location;LastModified=lastModified;优先级=优先级;输出是(根据你的评论,你正在寻找):12009-03-05T13:35:54.6468-07:00122009-03-06T13:35:54.6478-07:002我在插入时遇到问题将节点添加到具有多个命名空间的现有文档中无论我将命名空间设置为什么,每次都会添加xmlns引用属性。这打破了下游黑匣子。我最终通过做这样的事情解决了这个问题。XmlNodenewNode=newDoc.SelectSingleNode(xpathQuery,manager);newNode.Attributes.RemoveAll();node.ParentNode.InsertAfter(node.OwnerDocument.ImportNode(newNode,true),节点);您是否尝试过不在XmlRoot属性空间中指定名称?即:以上为C#学习教程:Xml序列化后,删除空的xmlns="",内容全部分享。如果对大家有用,需要进一步了解C#学习教程,希望大家多加关注——[XmlRoot(ElementName="url")]publicclassSitemapNode{...}本文收集自网络且不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:
