gpt4 book ai didi

c# - 如何使用 XML 序列化更改 XML 根名称?

转载 作者:数据小太阳 更新时间:2023-10-29 01:43:07 27 4
gpt4 key购买 nike

在使用 C# 进行 XML 序列化时,我试图更改根名称。

它总是采用类名而不是我尝试设置的名称。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{


MyTest test = new MyTest();
test.Test = "gog";

List<MyTest> testList = new List<MyTest>()
{
test
};

SerializeToXML(testList);
}

static public void SerializeToXML(List<MyTest> list)
{
XmlSerializer serializer = new XmlSerializer(typeof(List<MyTest>));
TextWriter textWriter = new StreamWriter(@"C:\New folder\test.xml");
serializer.Serialize(textWriter, list);
textWriter.Close();
}
}


}





using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;

namespace ConsoleApplication1
{

[XmlRootAttribute(ElementName = "WildAnimal", IsNullable = false)]
public class MyTest
{
[XmlElement("Test")]
public string Test { get; set; }


}
}

结果

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfMyTest xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<MyTest>
<Test>gog</Test>
</MyTest>
</ArrayOfMyTest>

它不会将其更改为 WildAnimal。我不确定为什么。这是我从教程中得到的。

编辑@Marc

谢谢。我现在明白你所做的事情看起来很奇怪,你必须在它周围做一个包装。我还有一个问题,如果我想制作这种格式会发生什么

<root>
<element>
<name></name>
</element>
<anotherElement>
<product></product>
</anotherElement>
</root>

就像一个嵌套的元素。我是否必须为第二部分创建一个新类并将其也粘贴到包装类中?

最佳答案

在您的示例中,MyTest 不是根;你想重命名数组吗?我会写一个包装器:

[XmlRoot("NameOfRootElement")]
public class MyWrapper {
private List<MyTest> items = new List<MyTest>();
[XmlElement("NameOfChildElement")]
public List<MyTest> Items { get { return items; } }
}

static void Main() {
MyTest test = new MyTest();
test.Test = "gog";

MyWrapper wrapper = new MyWrapper {
Items = { test }
};
SerializeToXML(wrapper);
}

static public void SerializeToXML(MyWrapper list) {
XmlSerializer serializer = new XmlSerializer(typeof(MyWrapper));
using (TextWriter textWriter = new StreamWriter(@"test.xml")) {
serializer.Serialize(textWriter, list);
textWriter.Close();
}
}

关于c# - 如何使用 XML 序列化更改 XML 根名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2125245/

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