我想弄清楚如何做XML序列化。XML序列化如何知道将属性放在哪里?
这是我多么希望我的XML文档太像到底
<course>
<name></name>
<backgroundColor></backgroundColor>
<fontColor></fontColor>
<sharingKey></sharingKey>
<task id="">
<taskName></taskName>
<description></description>
</task>
<task id="">
<taskName></taskName>
<description></description>
</task>
</course>
到目前为止,我的样子
<?xml version="1.0" encoding="utf-8"?>
<Course xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<name>name</name>
<backgroundColor>test</backgroundColor>
<fontColor>test2</fontColor>
<sharingKey>9324bfab-6cc7-49e5-84f7-56130b8dc099</sharingKey>
<task id="first Task" />
<task id="Second task" />
</Course>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
namespace ConsoleApplication1
{
[XmlRoot("Course")]
public class MyWrapper
{
public MyWrapper()
{
TaskList = new List<Tasks>();
}
[XmlElement("name")]
public string Name { get; set; }
[XmlElement("backgroundColor")]
public string BackgroundColor { get; set; }
[XmlElement("fontColor")]
public string FontColor { get; set; }
[XmlElement("sharingKey")]
public Guid SharingKey { get; set; }
[XmlElement("task")]
public List<Tasks> TaskList { get; set; }
}
public class Tasks
{
[XmlAttribute("id")]
public string Id { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Tasks task = new Tasks();
task.Id = "first Task";
Tasks task2 = new Tasks();
task2.Id = "Second task";
MyWrapper wrap = new MyWrapper();
wrap.BackgroundColor = "test";
wrap.FontColor = "test2";
wrap.Name = "name";
wrap.SharingKey = Guid.NewGuid();
wrap.TaskList.Add(task);
wrap.TaskList.Add(task2);
SerializeToXML(wrap);
}
static public void SerializeToXML(MyWrapper list)
{
XmlSerializer serializer = new XmlSerializer(typeof(MyWrapper));
TextWriter textWriter = new StreamWriter(@"C:\New folder\test.xml");
serializer.Serialize(textWriter, list);
textWriter.Close();
}
}
}
所以我的问题是与“ID “为了这个任务。
我只有在它与该另一个类
[XmlAttribute("id")]
public string Id { get; set; }
它怎么知道把这个属性在任务标签?
,如果我想有另一个属性
[XmlElement()]
public string TaskName {get; set;}
说我想和这个元素的属性会发生什么我怎么会确保该属性将与TASKNAME不工作?
哦,我不知道它是什么类型,但如果我手动编写xml文档没有什么会阻止我做 因此,对于C#序列化,我需要创建一个新的类和环绕那个?我可以看到一个例子,如果你需要将所有东西都包裹起来,那么看起来东西可能会变得很快混乱。 –
chobo2
2010-01-24 06:13:05
这与您已经使用MyWrapper类完成的工作没有什么不同。如果你有一个复合类型,只需创建一个类来表示它。在你的情况下,任务名称是一个字符串和ID号,因此创建一个名为TaskName的类,其中包含一个字符串和ID号。 – 2010-01-24 12:59:45
我的意思是说,每次你需要一个新的复合类型时,你都需要创建一个新类。所以如果你有许多复合类型,你将不得不使用X个类来查看整个代码。 – chobo2 2010-01-24 19:54:45