如何动态更改 XmlElement 名称?

How do I change the XmlElement name dynamically?

[XmlRoot("A")]
public class Foos
{
   [XmlElement("A1")]
   public List<Foo> FooList{ get; set; }
}


var serializer = new XmlSerializer(typeof(Foos));

这段代码也能正常工作。但它不是动态的。我想要 [XmlRoot("A")][XmlRoot(ConfigurationManager.AppSettings[someValue])]。但是会抛出语法错误。那我试试这个

    public class Foos
    {
       [XmlElement("A1")]
       public List<Foo> FooList{ get; set; }
    }
var serializer = new XmlSerializer(typeof(Foos),new XmlRootAttribute(ConfigurationManager.AppSettings[someValue]));

这只是 root element.I 的工作。我无法更改 FooList 的 "XmlElement" 值 dynamically.There 可以是 class 中的多个元素。如何动态更改所有这些的 XmlElement 值?

您需要以正确的方式使用 XmlAttributesOverrides。 Please Check

您的代码的工作版本在这里。

public class Foos
{       
    public List<Foo> FooList { get; set; }
}


public class Foo
{
    public string Name { get; set; }
}

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

        var xmlAttributeForFoos = new XmlAttributes { XmlRoot = new XmlRootAttribute(ConfigurationManager.AppSettings["someFoosValue"]), XmlType = new XmlTypeAttribute(ConfigurationManager.AppSettings["someFoosValue"]) };
        var xmlAttributeForFooList = new XmlAttributes();
        var xmlAttributeForFoo = new XmlAttributes();

        xmlAttributeForFooList.XmlElements.Add(new XmlElementAttribute(ConfigurationManager.AppSettings["someFooValue"]));
        xmlAttributeForFoo.XmlElements.Add(new XmlElementAttribute(ConfigurationManager.AppSettings["someFooNameValue"]));

         var overrides = new XmlAttributeOverrides();
        overrides.Add(typeof(Foos), xmlAttributeForFoos);
        overrides.Add(typeof(Foos), "FooList", xmlAttributeForFooList);
        overrides.Add(typeof(Foo), "Name", xmlAttributeForFoo);

        XmlSerializer serializer = new XmlSerializer(typeof(Foos), overrides);

        var foos = new Foos
        {
            FooList = new List<Foo>
            {
                new Foo{Name = "FooName"}
            }
        };

        using (var stream = File.Open("file.xml", FileMode.OpenOrCreate))
        {
            serializer.Serialize(stream, foos);
        }
    }
}

应用设置

<appSettings>
  <add key="someFoosValue" value="SomeFoos"/>    
  <add key="someFooValue" value="SomeFoo"/>
  <add key="someFooNameValue" value="FooName"/>
</appSettings>

输出

<SomeFoos xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <SomeFoo>
    <FooName>FooName</FooName>
  </SomeFoo>
</SomeFoos>