【问题标题】:Serialize type into XML from .NET从 .NET 将类型序列化为 XML
【发布时间】:2012-08-13 17:20:11
【问题描述】:

我有这个 C# 4.0 类型

public class DecimalField
{
    public decimal Value { get; set; }
    public bool Estimate { get; set; }
}

我想用XmlSerializer把类型序列化成

<Val Estimate="true">123</Val>

理想情况下,如果 Estimate 属性的值为 false,我想省略它。将 Estimate 更改为可为空的 bool 是可以接受的。

从这种类型转换到这种 XML 表示需要哪些属性/实现?

谢谢。

【问题讨论】:

  • 我认为使用一些属性可以完成这项工作。不知道属性是什么。

标签: c# .net xmlserializer ixmlserializable


【解决方案1】:

不确定是否可以仅使用属性有条件地输出 Estimate。但是你绝对可以实现 IXmlSerializable 并检查 WriteXml 方法中的 Estimate 值。

这是example

【讨论】:

    【解决方案2】:

    有条件地省略Estimate 需要大量的编码。我不会那样做的。

    XmlWriter writer = XmlWriter.Create(stream, new XmlWriterSettings() { OmitXmlDeclaration = true });
    
    var ns = new XmlSerializerNamespaces();
    ns.Add("", "");
    
    XmlSerializer xml = new XmlSerializer(typeof(DecimalField));
    
    xml.Serialize(writer, obj, ns);
    

    -

    [XmlRoot("Val")]
    public class DecimalField
    {
        [XmlText]
        public decimal Value { get; set; }
        [XmlAttribute]
        public bool Estimate { get; set; }
    }
    

    您也可以使用 Linq2Xml 手动序列化您的类

    List<XObject> list = new List<XObject>();
    list.Add(new XText(obj.Value.ToString()));
    if (obj.Estimate) list.Add(new XAttribute("Estimate", obj.Estimate));
    
    XElement xElem = new XElement("Val", list.ToArray());
    
    xElem.Save(stream);
    

    【讨论】:

      【解决方案3】:

      在不实现 IXmlSerializable 的情况下,这几乎是你所能得到的(总是包含一个 Estimate 属性):

      [XmlRoot("Val")]
      public class DecimalField
      {
          [XmlText()]
          public decimal Value { get; set; }
          [XmlAttribute("Estimate")]
          public bool Estimate { get; set; }
      }
      

      使用 IXmlSerializable,您的类如下所示:

      [XmlRoot("Val")]
      public class DecimalField : IXmlSerializable
      {
          public decimal Value { get; set; }
          public bool Estimate { get; set; }
      
          public void WriteXml(XmlWriter writer)
          {
              if (Estimate == true)
              {
                  writer.WriteAttributeString("Estimate", Estimate.ToString());
              }
      
              writer.WriteString(Value.ToString());
          }
      
          public void ReadXml(XmlReader reader)
          {
              if (reader.MoveToAttribute("Estimate") && reader.ReadAttributeValue())
              {
                  Estimate = bool.Parse(reader.Value);
              }
              else
              {
                  Estimate = false;
              }
      
              reader.MoveToElement();
              Value = reader.ReadElementContentAsDecimal();
          }
      
          public XmlSchema GetSchema()
          {
              return null;
          }
      }
      

      您可以像这样测试您的课程:

          XmlSerializer xs = new XmlSerializer(typeof(DecimalField));
      
          string serializedXml = null;
          using (StringWriter sw = new StringWriter())
          {
              DecimalField df = new DecimalField() { Value = 12.0M, Estimate = false };
              xs.Serialize(sw, df);
              serializedXml = sw.ToString();
          }
      
          Console.WriteLine(serializedXml);
      
          using (StringReader sr = new StringReader(serializedXml))
          {
              DecimalField df = (DecimalField)xs.Deserialize(sr);
      
              Console.WriteLine(df.Estimate);
              Console.WriteLine(df.Value);
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-03
        • 1970-01-01
        • 2011-04-06
        • 1970-01-01
        • 2012-10-01
        • 2020-12-09
        相关资源
        最近更新 更多