定义一个类如下:
public class Apple
{
public string Name { get; set; }
}使用如下序列化代码:
XmlSerializer ser = new XmlSerializer(typeof(Apple[])); using (MemoryStream ms = new MemoryStream())
{
ser.Serialize(ms, new Apple[] { new Apple() { Name = "红富士" } });
ms.Position = 0; using (StreamReader sr = new StreamReader(ms))
{
Console.Write(sr.ReadToEnd());
}
}
得到如下结果:
<?xml version="1.0"?>
<ArrayOfApple xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="h
ttp://www.w3.org/2001/XMLSchema">
<Apple>
<Name>红富士</Name>
</Apple>
</ArrayOfApple>我想定制跟节点和数组项的元素名称如下:
<?xml version="1.0"?>
<MyApples xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="h
ttp://www.w3.org/2001/XMLSchema">
<MyApple>
<Name>红富士</Name>
</MyApple>
</MyApples>我使用了如下代码:XmlAttributeOverrides overrides = new XmlAttributeOverrides();
XmlAttributes xas = new XmlAttributes();
xas.XmlArrayItems.Add(new XmlArrayItemAttribute("MyApple"));
overrides.Add(typeof(Apple[]), xas); XmlSerializer ser = new XmlSerializer(typeof(Apple[]), overrides, new Type[] { typeof(Apple) }, new XmlRootAttribute("MyApples"), ""); using (MemoryStream ms = new MemoryStream())
{
ser.Serialize(ms, new Apple[] { new Apple() { Name = "红富士" } });
ms.Position = 0; using (StreamReader sr = new StreamReader(ms))
{
Console.Write(sr.ReadToEnd());
}
}结果抛出异常:{"不能为类型 ConsoleApplication1.Apple[] 指定 XmlRoot 和 XmlType 属性。"}定制根节点的名称可以在XmlSerializer的构造函数中指定, 但是如何指定数组项的名称呢? 望高手不吝赐教。
public class Apple
{
public string Name { get; set; }
}使用如下序列化代码:
XmlSerializer ser = new XmlSerializer(typeof(Apple[])); using (MemoryStream ms = new MemoryStream())
{
ser.Serialize(ms, new Apple[] { new Apple() { Name = "红富士" } });
ms.Position = 0; using (StreamReader sr = new StreamReader(ms))
{
Console.Write(sr.ReadToEnd());
}
}
得到如下结果:
<?xml version="1.0"?>
<ArrayOfApple xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="h
ttp://www.w3.org/2001/XMLSchema">
<Apple>
<Name>红富士</Name>
</Apple>
</ArrayOfApple>我想定制跟节点和数组项的元素名称如下:
<?xml version="1.0"?>
<MyApples xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="h
ttp://www.w3.org/2001/XMLSchema">
<MyApple>
<Name>红富士</Name>
</MyApple>
</MyApples>我使用了如下代码:XmlAttributeOverrides overrides = new XmlAttributeOverrides();
XmlAttributes xas = new XmlAttributes();
xas.XmlArrayItems.Add(new XmlArrayItemAttribute("MyApple"));
overrides.Add(typeof(Apple[]), xas); XmlSerializer ser = new XmlSerializer(typeof(Apple[]), overrides, new Type[] { typeof(Apple) }, new XmlRootAttribute("MyApples"), ""); using (MemoryStream ms = new MemoryStream())
{
ser.Serialize(ms, new Apple[] { new Apple() { Name = "红富士" } });
ms.Position = 0; using (StreamReader sr = new StreamReader(ms))
{
Console.Write(sr.ReadToEnd());
}
}结果抛出异常:{"不能为类型 ConsoleApplication1.Apple[] 指定 XmlRoot 和 XmlType 属性。"}定制根节点的名称可以在XmlSerializer的构造函数中指定, 但是如何指定数组项的名称呢? 望高手不吝赐教。
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货