C# 序列化没有父标记的对象列表
我有一个包含5项的列表。我要做的就是创建一个xml,其中所有项目都显示如下:C# 序列化没有父标记的对象列表,c#,.net,xml,C#,.net,Xml,我有一个包含5项的列表。我要做的就是创建一个xml,其中所有项目都显示如下: <something> <someValue/> </something> <item>...</item> <item>...</item> <item>...</item> <item>...</item> <item>...</item> <so
<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");
}
}
[System.Xml.Serialization.XmlArrayAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified,IsNullable=true,Order=34)]
[System.Xml.Serialization.XmlArrayItemAttribute(“passengerDetails”,IsNullable=false)]
公共列表myListOfItems{
得到{
返回此.myListOfItemsField;
}
设置{
this.myListOfItemsField=值;
本.RaisePropertyChanged(“myListOfItems”);
}
}
如何才能省略父MyListFitems标记
编辑:
关于你提到的主题:
如果将XmlArrayItemAttribute更改为XmlElement,则会得到以下结果
InvalidOperationException:XmlElement、XmlText和XmlAnyElement不能与XmlAttribute、XmlAnyAttribute、XmlArray或XmlArrayItem一起使用
当我注释掉XmlArrayAttribute部分时,我得到了这个
InvalidOperationException:顺序不一致:如果在类的一个成员上使用,则所有类似粒子的成员都需要“Order”属性,请在类成员“item”上使用XmlElement、XmlAnyElement或XmlArray自定义属性显式设置“Order”
现在如何设置多个项目的订单?您不需要使用serialize。而是使用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();
}
}
}
使用System.Linq;
使用系统文本;
使用System.Xml;
使用System.Xml.Linq;
使用System.IO;
Net系统;
命名空间控制台应用程序73
{
班级计划
{
常量字符串文件名=@“c:\temp\test.xml”;
静态void Main(字符串[]参数)
{
XDocument doc=XDocument.Load(文件名);
列表项=文档子体(“项”)。选择(x=>(字符串)x.ToList();
}
}
}