我正在尝试将整数数组序列化为XML,但我无法让输出看起来像我想要的那样。我需要找到一些方法来覆盖数组中每个元素的元素名称 我到目前为止的代码:
var numbers = new int[]{1, 2, 3, 4, 5};
var serializer = new XmlSerializer(typeof(int[]), new XmlRootAttribute("rows"));
using (var stringWriter = new StringWriter())
{
serializer.Serialize(stringWriter, numbers);
Console.Write(stringWriter.ToString());
}
我追求的输出:
<?xml version="1.0" encoding="utf-16"?>
<rows xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<row>1</row>
<row>2</row>
<row>3</row>
<row>4</row>
<row>5</row>
</rows>
我看到的当前输出:
<?xml version="1.0" encoding="utf-16"?>
<rows xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<int>1</int>
<int>2</int>
<int>3</int>
<int>4</int>
<int>5</int>
</rows>
答案 0 :(得分:1)
您可以创建一个单独的类来保存您的值,您可以按如下方式指定Xml属性:
[Serializable]
[XmlRoot("rows")]
public class Rows
{
[XmlElement("row")]
public List<int> Elements { get; set; }
}
public static void SerializeOnScreen()
{
Rows numbers = new Rows();
numbers.Elements = new List<int>() { 1, 2, 3, 4, 5 };
var serializer = new XmlSerializer(typeof(Rows));
using (var stringWriter = new StringWriter())
{
serializer.Serialize(stringWriter, numbers);
Console.Write(stringWriter.ToString());
}
}