我需要帮助在C#/。net中序列化XML。
在C#中给出类似的内容:
public class Action {
public string Name;
public string Type;
}
public class TestObject {
public List<Action> Actions;
}
我想将动作列表序列化为元素,每个元素都有一个唯一的名称:
<TestObject>
<Action0>
<Name>A</Name>
<Type>Dog</Name>
</Action0>
<Action1>...</Action1>
<Action2>...</Action2>
...
</TestObject>
我一直在研究在自定义List对象上使用IXmlSerializable来替换TestObject。但我不确定如何进行。
这在正确的轨道上吗?
public class ActionCollection<T> : List<T>, IXmlSerializable ...
public class TestObject : ActionCollection<Action> { ...
这里是一个快速的解决方案,取决于您要寻找的维护级别:
var xml = new XmlDocument();
xml.LoadXml($@"
<TestObject>
<Action0>
<Name>A</Name>
<Type>Dog</Type>
</Action0>
<Action1>
<Name>B</Name>
<Type>Cat</Type>
</Action1>
<Action2>
<Name>C</Name>
<Type>Parrot</Type>
</Action2>
</TestObject>");
var actionsRaw = xml.ChildNodes[0].ChildNodes;
var test = new TestObject();
test.Actions = new List<Action>();
foreach (XmlNode action in actionsRaw)
{
test.Actions.Add(new Action
{
Name = action.ChildNodes[0].FirstChild.Value,
Type = action.ChildNodes[1].FirstChild.Value
});
}
如果名称和类型顺序颠倒,您可能会遇到麻烦,然后进行循环并在影响值之前检查节点的名称,但它似乎可以工作...
使用Xml Linq:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
TestObject tests = new TestObject() {
Actions = new List<Action>() {
new Action() { Name = "A", Type = "Dog"},
new Action() { Name = "C", Type = "Cat"},
new Action() { Name = "E", Type = "Elephant"}
}
};
string root = "<TestObject></TestObject>";
XDocument doc = XDocument.Parse(root);
XElement testObject = doc.Root;
int index = 0;
foreach (Action action in tests.Actions)
{
XElement newAction = new XElement("Action" + index.ToString(), new object[] {
new XElement("Name", action.Name),
new XElement("Type", action.Type)
});
testObject.Add(newAction);
index++;
}
doc.Save(FILENAME);
}
}
public class Action
{
public string Name;
public string Type;
}
public class TestObject
{
public List<Action> Actions;
}
}