如何动态更改XmlElement名称?

时间:2017-12-11 11:13:57

标签: c# serialization xml-serialization

[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]));

这只是根元素。我在工作。我无法动态更改FooList的“XmlElement”值。类中可以有多个元素。如何动态更改所有这些值的XmlElement值?

1 个答案:

答案 0 :(得分:1)

您需要以正确的方式使用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>