2017-01-17 17 views
0

シリアル化中にルールに基づいてXML要素名を変更しようとしています。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" /> 

答えて

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); 
     } 
関連する問題