C#序列化时如何给数组赋属性?我正在尝试生成像这样创建XML片段的C#。11:22:33:44:55:66:77:8811:22:33:44:55:66:77:8911:22:33:44:55:66:77:8A我正在考虑使用这类似于:[XmlArray("device_list"),XmlArrayItem("item")]publicListItem[]device_list{get;放;}作为属性,使用此类声明:publicclassListItem{[XmlAttribute]publicstringtype{get;放;}[XmlText]公共字符串值{get;放;这给了我内部序列化,但我不知道如何将type="list"属性应用于上面的device_list。我在想(但不确定如何编写语法)我需要做什么:publicclassDeviceList{[XmlAttribute]publicstringtype{get;放;}[XmlArray]publicListItem[]....这是我迷路的地方放;}}publicclassListItem{[XmlAttribute]publicstringtype{get;放;}[XmlText]公共字符串值{get;放;}}当前使用的是:[XmlArray("device_list"),XmlArrayItem("item")]publicDeviceListdevice_list{get;放;}和类型,尽管在代码中声明如下:device_list=newDeviceList{type="list"}device_list.Add(newListItem{type="MAC",Value="1234566"});device_list.Add(newListItem{type="MAC",Value="1234566"});不在序列化的显示类型中。这是序列化的结果:12345661234566显然我仍然遗漏了一些东西......使用上面Dave的部分答案,我发现最好在声明类中使用这个属性:(注意缺少的属性)publicDeviceListdevice_list{get;放;}然后像这样更新DeviceList类:[XmlType("device_list")][Serializable]publicclassDeviceList{[XmlAttribute]publicstringtype{get;放;}[XmlElement("item")]publicListItem[]items{get;放;}}并保留原来的ListItem类publicclassListItem{[XmlAttribute]publicstringtype{get;放;}[XmlText]公共字符串值{get;放;我的序列化符合预期:1234567123456890而不是使用ListItem[],从List派生一个名为DeviceList的新类:publicclassDeviceList:List{[XmlElement(ElementName="type")]publicstringListType{get;set;然后,在包含类中使用这个类来序列化XML。类型值可以作为元素包含在父节点中,具体取决于配置的序列化方式。我不记得确切的语法,但我认为类属性默认添加为节点元素。包含类:publicclassSerializeMyStuff{publicSeriazlieMyStuff(){ListOfDevices=newDeviceList();ListOfDevices.ListType="列表";您还可以通过在容器类中实现[IXmlSerializable][1]来实现所需的行为:使用下面的代码我得到以下标记:11:22:33:44:55:66:77:8811:22:33:44:55:66:77:8911:22:33:44:55:66:77:8A代码:publicclassItem{[XmlAttribute("type")]publicstringType{get;放;}[XmlText]公共字符串值{get;放;}}publicclassDeviceList:IXmlSerializable{publicstringType{get;放;}公共列表项{get;放;}publicSystem.Xml.Schema.XmlSchemaGetSchema(){返回空;}publicvoidReadXml(System.Xml.XmlReaderreader){reader.MoveToContent();}publicvoidWriteXml(System.Xml.XmlWriterwriter){writer.WriteAttributeString("type",Type);XmlSerializer序列化器=newXmlSerializer(typeof(Item));foreach(项目中的var项目){serializer.Serialize(writer,物品);我在主要方法中使用以下代码:vardlist=newDeviceList{Type="list",Items=newList{newItem{Type="MAC",Value="11:22:33:44:55:66:77:88"},新项目{Type="MAC",值="11:22:33:44:55:66:77:89"},新项目{Type="MAC",值="11:22:33:44:55:66:77:8A"},}};使用(FileStreamstream=newFileStream(@"D:jcoletest.xml",FileMode.Create,FileAccess.Write)){newXmlSerializer(typeof(DeviceList)).Serialize(stream,dlist);有关详细信息,请在此处查看本教程?分享的所有内容,如果对你有用,需要进一步了解C#学习教程,希望大家多多关注。本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如有转载请注明出处:
