1. 创建对象模型
根据实际的情况创建模型类。
[XmlRoot("Result")]
public class ResultModel
{
//要求不序列化属性
[XmlIgnore]
public string OrderNr;
[XmlAttribute("Id")]
public string MeterId;
//序列化为Xml子元素
[XmlElement("PointName")]
public string TestPointName;
}
2. 创建模型的实例
using System.Xml;
using System.Xml.Serialization;
using System.IO;
static void Main(string[] args)
{
ResultModel model = new ResultModel();
model.OrderNr = "04657524E0S";
model.MeterId = "123456";
model.TestPointName = "VoltageTest";
System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(model.GetType());
x.Serialize(Console.Out, model);
var fs = File.Create("Results.xml");
x.Serialize(fs, model);
Console.WriteLine();
Console.ReadLine();
}
效果如下:
在程序执行目录下:
将对象XML序列化存储在Result.xml文件中,和输出的内容一样。
<?xml version="1.0"?>
<Result xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" Id="123456">
<PointName>VoltageTest</PointName>
</Result>
网友评论