【问题标题】:Serialize a list of objects without the parent tag [duplicate]序列化没有父标签的对象列表[重复]
【发布时间】:2017-08-18 13:45:24
【问题描述】:

我有一个包含 5 个项目的列表 myListOfItems。我要做的就是创建一个xml,其中所有项目都像这样显示:

<something>
  <someValue/>
</something>

<item>...</item>
<item>...</item>
<item>...</item>
<item>...</item>
<item>...</item>

<somethingElse>
  <someValue/>
</somethingElse>

到目前为止,我有这个:

<something>
    <someValue/>
</something>

<myListOfItems>
  <item>...</item>
  <item>...</item>
  <item>...</item>
  <item>...</item>
  <item>...</item>
</myListOfItems>

<somethingElse>
  <someValue />
</somethingElse>

这就是我的做法:

[System.Xml.Serialization.XmlArrayAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=true, Order=34)]
[System.Xml.Serialization.XmlArrayItemAttribute("passengerDetails", IsNullable=false)]
public List<Item> myListOfItems {
    get {
        return this.myListOfItemsField;
    }
    set {
        this.myListOfItemsField = value;
        this.RaisePropertyChanged("myListOfItems");
    }
}

我该怎么做才能省略父 myListOfItems 标记?

编辑: 至于你提到的话题: 如果我将 XmlArrayItemAttribute 更改为 XmlElement 我会得到这个

InvalidOperationException:XmlElement、XmlText 和 XmlAnyElement 不能与 XmlAttribute、XmlAnyAttribute、XmlArray 或 XmlArrayItem 结合使用。

当我注释掉 XmlArrayAttribute 部分时,我得到了这个

InvalidOperationException:不一致的顺序:如果在类的成员之一上使用,则所有类似粒子的成员都需要“Order”属性,请在类成员“item”上使用 XmlElement、XmlAnyElement 或 XmlArray 自定义属性显式设置“Order” '。

现在如何设置多个项目的顺序?

【问题讨论】:

    标签: c# .net xml


    【解决方案1】:

    您不需要使用序列化。而是使用 xml linq :

    using System.Linq;
    using System.Text;
    using System.Xml;
    using System.Xml.Linq;
    using System.IO;
    using System.Net;
    
    
    namespace ConsoleApplication73
    {
        class Program
        {
            const string FILENAME = @"c:\temp\test.xml";
            static void Main(string[] args)
            {
    
                XDocument doc = XDocument.Load(FILENAME);
    
                List<string> items = doc.Descendants("item").Select(x => (string)x).ToList();
    
            }
    
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2019-03-01
      • 2021-06-18
      • 1970-01-01
      • 2021-10-09
      • 1970-01-01
      • 2019-08-28
      • 1970-01-01
      • 2012-07-14
      • 2019-08-28
      相关资源
      最近更新 更多