创建XML格式C# [英] Create xml format c#
本文介绍了创建XML格式C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在c#中制作这样的xml格式
I want to make xml format like this in c#
<?xml version='1.0' encoding='us-ascii'?>
<root>
<key value="22.wav">
<Index>1</Index>
<Index>20</Index>
<Index>21</Index>
</key>
<key value="EFG.wav">
<Index>5</Index>
<Index>22</Index>
</key>
</root>
我该如何形成表格,请帮助我
How do i form like this please help me
推荐答案
实现此目标的最佳方法是 XMLSerialization .如下所述创建一个属性类,并为其分配值:
Best way to achieve this is XMLSerialization. Create a property class as mentioned below and assign values to it :
[Serializable]
[XmlRoot("root")]
public class RootClass
{
[XmlElement("key")]
public List<KeyClass> key { get; set; }
}
[Serializable]
[XmlType("key")]
public class KeyClass
{
[XmlElementAttribute("value")]
public string KeyValue { get; set; }
[XmlElement("Index")]
public List<int> index { get; set; }
}
现在创建一个XML,如下所述:
Now create an XML as mentioned below :
static public void SerializeXML(RootClass details)
{
XmlSerializer serializer = new XmlSerializer(typeof(RootClass));
using (TextWriter writer = new StreamWriter(@"C:\Xml.xml"))
{
serializer.Serialize(writer, details);
}
}
如何使用SerializeXML方法分配值并生成XML:
// Create a New Instance of the Class
var keyDetails = new RootClass();
keyDetails.key = new List<KeyClass>();
// Assign values to the Key property
keyDetails.key.Add(new KeyClass
{
KeyValue = "22.wav",
index = new List<int> { 1, 2, 3}
});
keyDetails.key.Add(new KeyClass
{
KeyValue = "EFG.wav",
index = new List<int> { 5 , 22 }
});
// Generate XML
SerializeXML(keyDetails);
这篇关于创建XML格式C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文