动态更改Xml元素名称?

时间:2017-01-17 15:20:33

标签: c# xml generics reflection

我正在尝试在序列化期间根据规则更改Xml元素名称。

当然,我可以手动手动添加ElementName属性,但我的类中有超过1000个属性要序列化。

除此之外,我不想仅更改其中一些没有Xml ElementName属性的属性名称。

For Instance;

public class ToBeSerialized()
{
public string FirstName {get;set;}
public string LastName {get;set;}

[XmlElement(ElementName = "MyHome")]
public string Home {get;set;}

}

我的命名约定没有ElementName属性。

public string ChangeName(string item)
{
   if (!propName.Any(p => char.IsLower(p)))
            {
                return propName;
            }

            var builder = new StringBuilder();

            for (int i = 0; i < propName.Length; i++)
            {
                if (i != 0 && char.IsUpper(propName[i]))
                {
                    builder.Append("_");
                }

                builder.Append(propName[i].ToString().ToUpper(new CultureInfo("en-US", false)));
            }

            return builder.ToString();
}

所需的Xml

<ToBeSerialized First_Name="Name" Last_Name="Surname" MyHome="Mine" />

1 个答案:

答案 0 :(得分:0)

这是我的解决方案。 遍历对象属性,检查它是否已经有XmlElementAttribute,并且已经设置了它的ElementName。

如果不改变名称,则更改名称。

foreach (var prop in myObject.GetType().GetProperties())
            {
                var attribute = Attribute.GetCustomAttribute(prop, typeof(XmlElementAttribute)) as XmlElementAttribute;


                    XmlElementAttribute myElementAttribute = new XmlElementAttribute();
                    XmlAttributes myAttributes = new XmlAttributes();
                    if (attribute==null||attribute.ElementName.IsNullOrEmpty())
                    {
                        myElementAttribute.ElementName = prop.Name.NameToUpper();
                    }
                    if (prop.PropertyType == typeof(string))
                    {
                        myElementAttribute.IsNullable = true;
                    }
                    myAttributes.XmlElements.Add(myElementAttribute);
                    myOverrides.Add(typeof(myObject), prop.Name, myAttributes);
       }
相关问题