举个最简单的例子,比如一个XML内容如下:
<Message>
<Id>001</Id><Name>测试</Name>
<age>25</age>
</Message>
有个类结构如下:
public class Message
{
public string Id;
public string Name;
public string age;
}
要将XML的值自动填充到Message对象里去,只需三步
第一步,添加引用using GoLongSoft.XmlObjects;
[MappingTo("Message")]
public class Message : XmlItem
{
public string Id;
public string Name;
public string age;
}
System.Xml.XmlDocument xmlpostdata = new System.Xml.XmlDocument();
xmlpostdata.Load(Server.MapPath("xml.xml"));
string postData = xmlpostdata.InnerXml;
Message ms = new Message();
ms.FromXmlString(postData);
Response.Write(ms.Id+","+ms.Name+","+ms.age);
同样也可以反过来使用,(但需要给类里每个参数做标记[MappingAsNode(true)])代码如下:
[MappingTo("Message")]
public class Message : XmlItem
{
[MappingAsNode(true)]
public string Id;
[MappingAsNode(true)]
public string Name;
[MappingAsNode(true)]
public string age;
}
Message ms1 = new Message();
ms1.Id = "002";
ms1.Name = "测试2";
ms1.age = "20";
string temp = ms1.ToXmlString();
temp的值就为<Message><Name>测试2</Name><age>20</age><Id>002</Id></Message>
原文链接:https://www.f2er.com/xml/298086.html