gpt4 book ai didi

c# - 使用具有变量名称的项目反序列化数组

转载 作者:太空宇宙 更新时间:2023-11-03 10:34:45 25 4
gpt4 key购买 nike

我需要反序列化以下 XML 示例,但在尝试了一整天后我没有成功。

问题是元素名称不同,即使它们引用相同的原型(prototype)。

什么是最好的方法?

<Test Name="SomeName">
<OBJECTS NbObjects="2">
<OBJECT0 ObjectName="ObjName1">
<COMMAND NbCommand="3">
<COMMAND0 CommandLabel="Command_A" CommandFileName="File1"/>
<COMMAND1 CommandLabel="Command_B" CommandFileName="File2"/>
<COMMAND2 CommandLabel="Command_C" CommandFileName="File3"/>
</COMMAND>
</OBJECT0>
<OBJECT1 ObjectName="ObjName2">
<COMMAND NbCommand="8">
<COMMAND0 CommandLabel="MyCommand1" CommandFileName="File1"/>
<COMMAND1 CommandLabel="MyCommand2" CommandFileName="File2"/>
<COMMAND2 CommandLabel="MyCommand3" CommandFileName="File3"/>
<COMMAND3 CommandLabel="MyCommand4" CommandFileName="File4"/>
<COMMAND4 CommandLabel="MyCommand5" CommandFileName="File5"/>
<COMMAND5 CommandLabel="MyCommand6" CommandFileName="File6"/>
<COMMAND6 CommandLabel="MyCommand7" CommandFileName="File7"/>
<COMMAND7 CommandLabel="MyCommand8" CommandFileName="File8"/>
</COMMAND>
</OBJECT1>
</OBJECTS>
</Test>

这是我正在尝试但没有成功的 C# 代码:

using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;

namespace XMLtest
{
[XmlRoot("Test")]
public class Test
{
[XmlAttribute("Name")]
public string Name { get; set; }
[XmlElement("OBJECTS")]
public Objects objects { get; set; }

public void Load(string filename)
{
XmlSerializer xs = new XmlSerializer(typeof (Test));
using (StreamReader rd = new StreamReader(filename))
{
Test test = xs.Deserialize(rd) as Test;
}
}
}

public class Objects
{
[XmlAttribute("NbObjects")]
public int NbObjects { get; set; }
[XmlArray]
[XmlArrayItem(typeof(Object))]
public List<Object> ObjectList { get; set; }

public Objects()
{
ObjectList = new List<Object>();
}
}

public class Object
{
[XmlAttribute("ObjectName")]
public string ObjectName { get; set; }

[XmlElement("COMMAND")]
public Commands Cmds { get; set; }
}

public class Commands
{
[XmlAttribute("NbCommand")]
public int NbCommand { get; set; }

[XmlArray("COMMAND")]
[XmlArrayItem("COMMAND")]
public List<Command> CommandList { get; set; }

public Commands()
{
CommandList = new List<Command>();
}
}

public class Command
{
[XmlAttribute("CommandLabel")]
public string CommandLabel { get; set; }

[XmlAttribute("CommandFileName")]
public string CommandFileName { get; set; }
}
}

最佳答案

我的建议是不要使用 <OBJECT0 ... > , <OBJECT1 ... ><COMMAND0 ... > , <COMMAND1 ... >等等。这些是不同的标签,表示不同的项目/对象。

如果数字对您很重要,请将项目更改为 <OBJECT id='0' name='...'> ... </OBJECT><COMMAND id='0' label='...' filename='...' > ... </COMMAND> .这将使您能够通过 id 对它们进行排序或识别,并且所有标签都属于同一类型。

关于c# - 使用具有变量名称的项目反序列化数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28195794/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com