Skip to main content
 首页 » 编程设计

C# 将简单对象序列化为 xml。没有命名空间没有空值

2024年02月23日19飞鱼

我得到了以下代码:

public class Alarm:IDisposable 
{ 
    MemoryStream _tmp; 
    readonly XmlDocument _doc; 
    private readonly XmlSerializerNamespaces _ns; 
    private readonly XmlSerializer _x = new  XmlSerializer(typeof(Alarm)); 
    public int? ID { get; set; } 
    public string SourceSystem { get; set; } 
    public string SensorName { get; set; } 
    public string ModelName { get; set; } 
    public int? Severity { get; set; } 
    public int? Duration { get; set; } 
    public bool? Status { get; set; } 
    public DateTime? StartTime { get; set; } 
    public DateTime? EndTime { get; set; } 
 
    public Alarm() 
    { 
        _tmp = new MemoryStream(); 
        _doc = new XmlDocument(); 
        _ns = new XmlSerializerNamespaces(); 
        _ns.Add("", ""); 
    } 
    public string OuterXml() 
    { 
 
        //Add an empty namespace and empty value 
        _x.Serialize(_tmp, this, _ns); 
        _tmp.Position = 0; 
        _doc.Load(_tmp); 
        return _doc.OuterXml; 
    } 
 
 
    public void Dispose() 
    { 
        if (_tmp!=null) 
        { 
            _tmp.Close(); 
            _tmp = null; 
        } 
 
    } 
} 

我得到输出”

 <?xml version=\"1.0\"?> 
 <Alarm><ID>1</ID><SourceSystem>HMer</SourceSystem> 
 <SensorName>4</SensorName><Severity d2p1:nil=\"true\" xmlns:d2p1=\"http://www.w3.org/2001/XMLSchema-instance\" /> 
 <Duration>500</Duration><Status>true</Status> 
 <StartTime>2011-07-19T12:29:51.171875+03:00</StartTime> 
<EndTime d2p1:nil=\"true\"  
 xmlns:d2p1=\"http://www.w3.org/2001/XMLSchema-instance\" /></Alarm> 

我想得到:

<Alarm><ID>1</ID><SourceSystem>HMer</SourceSystem><SensorName>4</SensorName> 
<Duration>500</Duration><Status>true</Status> 
<StartTime>2011-07-19T12:29:51.171875+03:00</StartTime></Alarm> 

意思是没有 xmlns 的东西,没有值为 null 的标签。

请帮帮我

请您参考如下方法:

将以下属性添加到您的可空字段:

[XmlIgnore] 
public bool EndTimeSpecified { get { return EndTime.HasValue; } } 

这让 XmlSerializer(它对 Nullable 字段有点笨)意识到没有指定 EndTime,因此,该字段不需要序列化。

这是 documentation of this feature :

Another option is to use a special pattern to create a Boolean field recognized by the XmlSerializer, and to apply the XmlIgnoreAttribute to the field. The pattern is created in the form of propertyNameSpecified. For example, if there is a field named "MyFirstName" you would also create a field named "MyFirstNameSpecified" that instructs the XmlSerializer whether to generate the XML element named "MyFirstName".

这是一个提供更多详细信息和解释的相关 SO 问题:

关于删除 XML 处理指令(即 <?xml ... ?> 部分),还有一个 SO 问题: