我有这个对象
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格式必须始终有一个根节点。如果要更改根节点名称,可以使用根类的XmlRoot属性。
[XmlRoot("AnotherName")]
public class Root
{
[XmlElement("Items")]
public List<Items> Items { get; set; }
}
我同意其他评论,这听起来像一个坏主意!但是,如果你像你说的那样被困住了,我认为你可以尝试这样做:
string xml = myObj.Items.Aggregate(seed: new StringBuilder(),
func: (builder, item) =>
{
using var writer = new StringWriter();
new XmlSerializer(typeof(Items))
.Serialize(writer, item);
return builder.AppendLine(writer.ToString());
}).ToString();
当您想要一些不寻常的结构化XML时,您就违背了XmlSerializer的意图。但是我们仍然可以使用它来构建有效的序列化XML片段。该解决方案使用StringBuilder将这些有效的片段聚合为单个字符串。
为简单起见,我使用了StringWriter,但您可以根据需要插入XmlWriter等,以获得漂亮的打印。