xmlserializer
作成したいxmlの階層に合わせてクラスを作成
出力したい最上位の階層をxmlserializerに指定する
途中の 「namespaces.Add(string.Empty, string.Empty);」は、xmlに出力されるnamespacesを非表示にできる
xmlを出力するソース
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Xml.Serialization;
namespace Sample
{
[XmlRoot("Root")]
public class Root : Collection<Element>
{
[XmlElement("Element")]
public Element Element
{
get; set;
}
}
public class Element
{
[XmlAttribute("Attribute_A")]
public int Attribute_A
{
get; set;
}
[XmlArray("Array")]
[XmlArrayItem("ArrayItem")]
public List<ArrayItem> Array
{
get; set;
}
}
public class ArrayItem
{
[XmlAttribute("Attribute_B")]
public string Attribute_B
{
get; set;
}
}
public class Program
{
public static void Main(string[] args)
{
var Root = new Root
{
new Element
{
Attribute_A = 123,
Array = new List<ArrayItem>
{
new ArrayItem{ Attribute_B="text"}
}
},
};
string fileName = @"C:\create.xml";
var serializer = new XmlSerializer(typeof(Root));
var namespaces = new XmlSerializerNamespaces();
namespaces.Add(string.Empty, string.Empty);
StreamWriter streamWriter = new StreamWriter(fileName, false, new System.Text.UTF8Encoding(false));
serializer.Serialize(streamWriter, Root, namespaces);
streamWriter.Close();
}
}
}
出力されるxmlファイルの中身
<?xml version="1.0" encoding="utf-8"?>
<Root>
<Element Attribute_A="123">
<Array>
<ArrayItem Attribute_B="text" />
</Array>
</Element>
</Root>