gpt4 book ai didi

c# - 如何将以下类对象制作成xml?

转载 作者:太空宇宙 更新时间:2023-11-03 13:52:01 25 4
gpt4 key购买 nike

我有以下类(class)。 (SIM 模型、产品、项目)

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>

如何使用上层类制作模拟 XML?我不知道如何包装每个类..

最佳答案

我做了一个简单的序列化方法,序列化为字符串并删除 namespace 。

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>

关于c# - 如何将以下类对象制作成xml?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13438185/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com