问题描述
我有一个实体如下
public class Vehicle{
public int VehicleId {get;set;};
public string Make {get;set;};
public string Model{get;set;}
}
我想序列化如下
<Vehicle>
<VehicleId AppliesTo="C1">1244</VehicleId>
<Make AppliesTo="Common" >HXV</Make>
<Model AppliesTo="C2">34-34</Model>
</Vehicle>
我在 Vehicle 类中有大约 100 个这样的属性,对于每个车辆属性,我想附加一个元数据 ApplieTo,这将有助于下游系统.AppliesTo 属性是静态的,其值是在设计时定义的.现在如何将 AppliesTo 元数据附加到每个属性并依次序列化为 XML?
I have around 100 properties like this in Vehicle class, for each vehicle property I wanted to attach a metadata ApplieTo which will be helpful to downstream systems. AppliesTo attribute is static and its value is defined at the design time. Now How can I attach AppliesTo metadata to each property and inturn get serialized to XML?
推荐答案
您可以使用 XElement
来自 System.Xml.Linq
来实现这一点.由于您的数据是静态的,您可以轻松地分配它们.下面的示例代码 -
You can use XElement
from System.Xml.Linq
to achieve this. As your data is static you can assign them easily. Sample code below -
XElement data= new XElement("Vehicle",
new XElement("VehicleId", new XAttribute("AppliesTo", "C1"),"1244"),
new XElement("Make", new XAttribute("AppliesTo", "Common"), "HXV"),
new XElement("Model", new XAttribute("AppliesTo", "C2"), "34 - 34")
);
//OUTPUT
<Vehicle>
<VehicleId AppliesTo="C1">1244</VehicleId>
<Make AppliesTo="Common">HXV</Make>
<Model AppliesTo="C2">34 - 34</Model>
</Vehicle>
如果您对 System.Xml.Linq
不感兴趣,那么您还有另一个选择 XmlSerializer
类.为此,您需要为 vehicle
的每个属性定义单独的类.以下是示例代码,您可以为 Make 和 Model
-
If you are not interested in System.Xml.Linq
then you have another option of XmlSerializer
class. For that you need yo define separate classes for each property of vehicle
. Below is the sample code and you can extend the same for Make and Model
-
[XmlRoot(ElementName = "VehicleId")]
public class VehicleId
{
[XmlAttribute(AttributeName = "AppliesTo")]
public string AppliesTo { get; set; }
[XmlText]
public string Text { get; set; }
}
[XmlRoot(ElementName = "Vehicle")]
public class Vehicle
{
[XmlElement(ElementName = "VehicleId")]
public VehicleId VehicleId { get; set; }
//Add other properties here
}
然后创建测试数据并使用XmlSerializer
类构造XML -
Then create test data and use XmlSerializer
class to construct XML -
Vehicle vehicle = new Vehicle
{
VehicleId = new VehicleId
{
Text = "1244",
AppliesTo = "C1",
}
};
XmlSerializer testData = new XmlSerializer(typeof(Vehicle));
var xml = "";
using (var sww = new StringWriter())
{
using (XmlWriter writer = XmlWriter.Create(sww))
{
testData.Serialize(writer, vehicle);
xml = sww.ToString(); // XML
}
}
这篇关于带有附加元数据的类属性的 XML 序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!