gpt4 book ai didi

c# - 在 C# 中没 Root过的 XmlSerialisation

转载 作者:行者123 更新时间:2023-12-05 05:39:49 25 4
gpt4 key购买 nike

我有这个对象

var myObj = new Root
{
Items = new List<Items>
{
new Items { MyValue1 = "test", MyValue2 = 22 },
new Items { MyValue1 = "test2", MyValue2 = 44 },
}
};

public class Root
{
public List<Items> Items { get; set; }
}

public class Items
{
public string MyValue1 { get; set; }
public int MyValue2 { get; set; }
}

我可以这样序列化它:

<Root>
<Items>
<Items>
<MyValue1>test</MyValue1>
<MyValue2>22</MyValue2>
</Items>
<Items>
<MyValue1>test2</MyValue1>
<MyValue2>44</MyValue2>
</Items>
</Items>
</Root>

但我想像这样序列化:

<Items>
<MyValue1>test</MyValue1>
<MyValue2>22</MyValue2>
</Items>
<Items>
<MyValue1>test2</MyValue1>
<MyValue2>44</MyValue2>
</Items>

但是我找不到办法做到这一点

这是复制代码:

class Program
{
static void Main(string[] args)
{
var myObj = new Root
{
Items = new List<Items>
{
new Items { MyValue1 = "test", MyValue2 = 22 },
new Items { MyValue1 = "test2", MyValue2 = 44 },
}
};

var serializer = new XmlSerializer(typeof(Root));
var ms = new MemoryStream();
var settings = new XmlWriterSettings { Encoding = new UTF8Encoding(false), OmitXmlDeclaration = true };
using var xmlWriter = XmlWriter.Create(ms, settings);
var ns = new XmlSerializerNamespaces();
ns.Add(string.Empty, string.Empty);
serializer.Serialize(xmlWriter, myObj, ns);

var xmlDebug = Encoding.UTF8.GetString(ms.ToArray());

var result = @"<?xml version=""1.0"" encoding=""utf-8""?><Items><MyValue1>test</MyValue1><MyValue2>22</MyValue2></Items><Items><MyValue1>test2</MyValue1><MyValue2>44</MyValue2></Items>";
Assert.AreEqual(result, xmlDebug);

}
}

public class Root
{
public List<Items> Items { get; set; }
}

public class Items
{
public string MyValue1 { get; set; }
public int MyValue2 { get; set; }
}

最佳答案

您可以在数据模型中使用 xml 属性。

public class Root
{
[XmlElement("Items")]
public List<Items> Items { get; set; }
}

public class Items
{
public string MyValue1 { get; set; }
public int MyValue2 { get; set; }
}

“列表”的默认 xml 属性是 XmlArrayItem,如果您为其使用 XmlElement,这将是您的结果

<Root>
<Items>
<MyValue1>test</MyValue1>
<MyValue2>22</MyValue2>
</Items>
<Items>
<MyValue1>test2</MyValue1>
<MyValue2>44</MyValue2>
</Items>
</Root>

并且xml格式必须始终有一个根节点。如果要更改根节点名称,可以使用 Root 类的 XmlRoot 属性。

[XmlRoot("AnotherName")]
public class Root
{
[XmlElement("Items")]
public List<Items> Items { get; set; }
}

关于c# - 在 C# 中没 Root过的 XmlSerialisation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72574234/

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