我有下课。 (SIMModel,产品,项目)
public class SIMModel
{
public Product Product { get; set; }
}
public class Product
{
public List<Item> Items { get; set; }
}
public class Item
{
[XmlAttribute("ID")]
public String ID { get; set; }
[XmlAttribute("Name")]
public String Name { get; set; }
public Child_Item Child_Item { get; set; }
public Parent_Item Parent_Item { get; set; }
}
public class Child_Item
{
[XmlAttribute("ID")]
public String ID { get; set; }
}
我想制作这个XML
<SIMModel>
<Product>
<Item ID="N" Name="N-1">
<Child_Item ID="N-1-1">
</Item>
</Proudct>
</SIMModel>
如何使用上层类创建Simulation XML? 我不知道如何包装每个班级。
答案 0 :(得分:1)
我创建了一个简单的Serialize方法,它序列化为字符串并删除命名空间。
private static void Main(string[] args)
{
string result = Serialize(new SIMModel
{
Product = new Product
{
Items = new List<Item>
{
new Item
{
ID = "N",
Name = "N-1",
Child_Item = new Child_Item {ID = "N-1-1"}
}
}
}
});
Console.WriteLine(result);
}
public static string Serialize<T>(T value)
{
if (value == null)
{
return null;
}
//Create our own namespaces for the output
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
//Add an empty namespace and empty value
ns.Add("", "");
XmlSerializer serializer = new XmlSerializer(typeof (T));
XmlWriterSettings settings = new XmlWriterSettings
{
Encoding = new UnicodeEncoding(false, false),
Indent = true,
OmitXmlDeclaration = true
};
using (StringWriter textWriter = new StringWriter())
{
using (XmlWriter xmlWriter = XmlWriter.Create(textWriter, settings))
{
serializer.Serialize(xmlWriter, value, ns);
}
return textWriter.ToString();
}
}
输出:
<SIMModel>
<Product>
<Items>
<Item ID="N" Name="N-1">
<Child_Item ID="N-1-1" />
</Item>
</Items>
</Product>
</SIMModel>