【问题标题】:Deserialize XML either with or without Namespace使用或不使用命名空间反序列化 XML
【发布时间】:2022-01-03 08:33:01
【问题描述】:

我有几个xml 文件进来。有些有命名空间,有些没有。如何准确地转换这些而不会出现异常。

这是我的代码:

SASBM XML:

<ExportData xmlns="http://www.w3.org/2001/XMLSchema-instance">
    <SASBM>...</SASBM>
</ExportData>

SASCS XML:

<ExportData>
    <SASCS>...</SASCS>
</ExportData>

我的 XML 反序列化器:

_xmlSerializer = new XmlSerializer(typeof(ExportData));
_xmlSerializer.Deserialize(sr);

var tst = _xmlSerializer.Deserialize(sr);

还有我的班级:

/// <remarks/>
[System.Serializable()]
[System.ComponentModel.DesignerCategory("code")]
[System.Xml.Serialization.XmlType(AnonymousType = true)]
[System.Xml.Serialization.XmlRoot(Namespace = "http://www.w3.org/2001/XMLSchema-instance", IsNullable = false)]
public partial class ExportData
{
    /// <remarks/>
    public byte PlantCode { get; set; }

    /// <remarks/>
    public byte ServerID { get; set; }

    /// <remarks/>
    public uint MessageNumber { get; set; }

    /// <remarks/>
    public ExportDataSASAH SASAH { get; set; }

    /// <remarks/>
    public ExportDataSASCS SASCS { get; set; }

    /// <remarks/>
    public ExportDataSASBM SASBM { get; set; }
}

namespace 设置为namespace="" 会针对一种文件类型修复它,但在第二种文件类型上出现异常。而且我不知道添加多个命名空间选项的方法。

【问题讨论】:

    标签: c# xml serialization


    【解决方案1】:

    解决方法是重写 XMLSerializer 命名空间函数

    // helper class to ignore namespaces when de-serializing
    public class NamespaceIgnorantXmlTextReader : XmlTextReader
    {
        public NamespaceIgnorantXmlTextReader(TextReader reader) : base(reader)
        {
        }
    
        public override string NamespaceURI
        {
            get { return ""; }
        }
    }
    

    然后移除命名空间属性:

    [System.Xml.Serialization.XmlRoot(Namespace = "http://www.w3.org/2001/XMLSchema-instance", IsNullable = false)]
    

    最后解析如下:

    _xmlSerializer.Deserialize(new NamespaceIgnorantXmlTextReader(sr));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-02
      • 2015-06-28
      • 1970-01-01
      • 2019-10-12
      • 1970-01-01
      相关资源
      最近更新 更多