【问题标题】:Unwanted Property Name With XML Serialization [duplicate]带有 XML 序列化的不需要的属性名称 [重复]
【发布时间】:2011-12-07 20:56:54
【问题描述】:

可能重复:
Removing Wrapper Elements from XML-Serialized Array

这很难解释,所以我举了一个我的问题的例子。我有一个包含子类列表的父类。当我序列化父类时,我得到了我的子类,但它们位于具有公共属性名称的元素下。额外的水平不是我需要的。我尝试将 XmlIgnore 属性添加到属性名称,但这会抑制属性名称及其包含的发票集合的所有内容。

父类:

[XmlRoot("header")]
public class Lynx : INotifyPropertyChanged
{

    #region /*-- Class Fields --*/

    private List<InvoiceItem> _invoice = new List<InvoiceItem>();

    #endregion

    [XmlArray("invoice")]
    [XmlArrayItem("invoice", typeof(InvoiceItem))]
    public List<InvoiceItem> invoice
    {
        get
        {
            return _invoice;
        }
        set
        {
            if (value != _invoice)
            {
                _invoice = value;
                OnPropertyChanged("invoice");
            }
        }
    }

儿童班:

[XmlType(TypeName = "invoice")]
public class InvoiceItem : INotifyPropertyChanged
{
    ... properties and methods of the class
}

这是它正在构建的:

<header>
    <headerid>790aa61a-ad1b-49b9-bfb9-01fe3ca55eca</headerid>
    <invoice>  <-- this line is not needed
        <invoice>
            <company>BRU111</company>
            <format>myformat</format>
            ...

这是我需要构建的:

<header>
    <headerid>790aa61a-ad1b-49b9-bfb9-01fe3ca55eca</headerid>
    <invoice>
        <company>BRU111</company>
        <format>myformat</format>
        ...

【问题讨论】:

  • (删除了我的答案,因为@Tuzo 发现了一个很好的现有副本,但是:使用[XmlElement("invoice")] 而不是您当前的属性)
  • @Tuzo - 很好的发现,谢谢,我无法很好地表达这个问题,无法找到另一个。

标签: c# xml serialization xml-serialization


【解决方案1】:

创建额外元素的原因是因为您的属性是一个项目列表

如果你想要一个奇异值,使用

公共 InvoiceItem 发票
{

而不是

公开列表 发票
{

集合总是放置一个容器,这样每一项都放在容器节点下。

【讨论】:

  • 标题元素将包含 1+ 个发票元素,所以我确实想要一个发票集合。
猜你喜欢
  • 2015-09-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-25
  • 1970-01-01
  • 1970-01-01
  • 2016-02-11
相关资源
最近更新 更多