【问题标题】:C# XML Serialization XMLElement without tag没有标签的 C# XML 序列化 XMLElement
【发布时间】:2016-09-14 07:16:35
【问题描述】:

我有以下课程:

[Serializable]
public class SomeModel
{
    [XmlElement("CustomerName")]
    public string CustomerName { get; set; }

    [XmlElement("")]
    public int CustomerAge { get; set; }
}

使用 XmlSerializer.Serialize() 进行序列化(填充一些测试数据时)会产生以下 XML:

<SomeModel>
  <CustomerName>John</CustomerName>
  <CustomerAge>55</CustomerAge>
</SomeModel>

我需要的是:

<SomeModel>
  <CustomerName>John</CustomerName>
   55
</SomeModel>

意思是第二个xmlelement,它不应该有自己的标签。这甚至可能吗?谢谢。

【问题讨论】:

  • 为什么要这样做?当您将此 xml 转换回 SameModel 类时,它将没有 CustomerAge。
  • 我的应用使用的 API 需要这种 XML 结构
  • 你试过[XmlText]吗?见stackoverflow.com/questions/9504150/…
  • XmlSerializer 不需要 [Serializable]。它用于指示 BinaryFormatter。
  • 谢谢,但我在序列化时点击了“反映类型错误”

标签: c# .net xml serialization xml-serialization


【解决方案1】:

XmlText而不是XmlElement装饰CustomerAge

您还必须将 CustomerAge 的类型从 int 更改为 string,如果您不想这样做,则必须采用额外的属性进行序列化,如下所示:

public class SomeModel
{
    [XmlElement("CustomerName")]
    public string CustomerName { get; set; }

    [XmlText]
    public string CustomerAgeString { get { return CustomerAge.ToString(); } set { throw new NotSupportedException("Setting the CustomerAgeString property is not supported"); } }

    [XmlIgnore]
    public string CustomerAge { get; set; }
}

【讨论】:

  • 谢谢,但我在序列化时点击了“反映类型错误”
  • 您可以将 CustomerAge 的类型从 int 更改为 String 吗?
  • 非常感谢!你是救生员!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多