本文介绍了使用名称HIde null XML元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 您好我有一个XML文件如下 < sun / > < mon start = 3:00 PM end = 11:00 PM / > < tue start = 3:00 PM end = 11:00 PM / > 在Sun标签中我设置了[XmlElement(ElementName =sun,IsNullable = false) )] 但它仍显示< sun>标签 。我想删除这个也请帮帮我 我的代码如下: [XmlElement(ElementName = sun,IsNullable = false )] public RestaurantDay Sunday { 获得; set ; } public class RestaurantDay { [XmlAttribute(AttributeName = start)] public string 开始{获取; set ; } [XmlAttribute(AttributeName = end)] public string 结束{ get ; set ; } } 解决方案 请阅读文档 [ ^ ]。即使文档可以为空,它也必须是可见的。 为了能够删除xml元素,你必须创建xsd文件,你必须以这种方式声明这个元素: < xs:element 名称 = sun type = xs:string minoccurs = 0 maxoccurs = 无界 xmlns:xs = #unknown / > 这意味着 sun 元素是可选的(不是必需的)。 请参阅:使用属性控制XML序列化 [ ^ ] 控制XML序列化的属性 [ ^ ] <xsd:attribute xmlns:xsd =#unknown>< xsd:attribute>元素 [ ^ ] 使用 System.ComponentModel.DefaultValueAttribute 赞 [DefaultValue( 0 )] public int sun { get ; set ; } 或者如果'Sun'是类或自定义类型,则将类似的内容添加到序列化类中 public bool ShouldSerializeSun(){ return sun!= null ; } 请参阅: https://msdn.microsoft.com/en-US/library/53b8022e%28v=vs.110%29.aspx [ ^ ] Hi I have an XML file like following <sun/><mon start="3:00 PM" end="11:00 PM"/><tue start="3:00 PM" end="11:00 PM"/>in Sun tag i have set [XmlElement(ElementName = "sun",IsNullable=false)]but it still shows the <sun> tag . I want to remove this also Please help memy code like following [XmlElement(ElementName = "sun", IsNullable = false)] public RestaurantDay Sunday { get; set; }public class RestaurantDay{ [XmlAttribute(AttributeName = "start")] public string Start { get; set; } [XmlAttribute(AttributeName = "end")] public string End { get; set; } } 解决方案 Please read the documentation[^]. Even if document is nullable it must be "visible".To be able to "remove" xml element, you have to create xsd file, in which you have to declare this element that way:<xs:element name="sun" type="xs:string" minoccurs="0" maxoccurs="unbounded" xmlns:xs="#unknown" />It means that sun element is optional (not required).See: Controlling XML Serialization Using Attributes[^]Attributes That Control XML Serialization[^]<xsd:attribute xmlns:xsd="#unknown"><xsd:attribute> Element[^]Use System.ComponentModel.DefaultValueAttributelike[DefaultValue(0)] public int sun { get; set; }or if 'Sun' is a class or customtype add something like this to your serialized classpublic bool ShouldSerializeSun() { return sun != null;}See: https://msdn.microsoft.com/en-US/library/53b8022e%28v=vs.110%29.aspx[^] 这篇关于使用名称HIde null XML元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 10-19 22:29