[英]Changing Xml Element Name Dynamically?
我正在尝试根据序列化过程中的规则更改Xml元素名称。
当然,我可以手动添加ElementName属性,但是我的类中有1000多个属性需要序列化。
除此之外,我不想更改所有属性名称,而只更改其中一些不具有Xml ElementName属性的属性名称。
例如 ;
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" />
这是我的解决方案。 遍历对象属性检查它是否已经具有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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.