如何解决序列化具有对象类型属性的类
Type 对象的属性值可以是任何类型的单个值,如 int、string、decimal 等,也可以是 List
public class Criteria
{
[XmlElement("IDS")]
public object Value
{
get; set;
}
}
电流输出:
<CriteriaGroup>
<Criteria p2:type="Criteria" xmlns:p2="http://www.w3.org/2001/XMLSchema-instance">
<IDS p2:type="ArrayOfInt">
<int>2610</int>
<int>2452</int>
</IDS>
</Criteria>
<Criteria p2:type="Criteria" xmlns:p2="http://www.w3.org/2001/XMLSchema-instance">
<IDS p2:type="ArrayOfString">
<string>CUMULU1MO</string>
<string>ALLIEDWX2</string>
</IDS>
</Criteria>
</CriteriaGroup>
预期输出:
我怎样才能达到以下结果?尝试用 XmlArray、XmlArrayItem 装饰公共对象值,但没有成功。
<CriteriaGroup>
<Criteria>
<IDS>
<ID>2610</ID>
<ID>2452</ID>
</IDS>
</Criteria>
<Criteria>
<IDS>
<ID>CUMULU1MO</ID>
<ID>ALLIEDWX2</ID>
</IDS>
</Criteria>
</CriteriaGroup>
使用下面的方法进行序列化。
public static string Serialize<T>(T data)
{
string xmlData = string.Empty;
XmlSerializer ser = new XmlSerializer(typeof(T));
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("","");
var settings = new XmlWriterSettings();
settings.Indent = true;
settings.OmitXmlDeclaration = true;
using (StringWriter sw = new StringWriter())
{
using (XmlWriter xw = XmlWriter.Create(sw,settings))
{
ser.Serialize(xw,data,ns);
xmlData = sw.ToString();
}
}
return xmlData;
}
解决方法
尝试以下操作:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
CriteriaGroup CriteriaGroup = new CriteriaGroup()
{
Criteria = new List<Criteria>() {
new Criteria() { Value = new string[] { "2610","2452"}
},new Criteria() { Value = new string[] {"CUMULU1MO","ALLIEDWX2"}
}
}
};
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
XmlWriter writer = XmlWriter.Create(FILENAME,settings);
XmlSerializer serializer = new XmlSerializer(typeof(CriteriaGroup));
serializer.Serialize(writer,CriteriaGroup);
}
}
public class CriteriaGroup
{
[XmlElement()]
public List<Criteria> Criteria { get; set; }
}
public class Criteria
{
[XmlArray("IDS")]
[XmlArrayItem("ID")]
public string[] Value
{
get;
set;
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。