2016-09-14 35 views
0

林与<元素行为=“替换”> XML元素试图重新创建XML它的结果应该是这个样子:创建在C#

<names> 
    <legalName behavior="replace"> 
     <firstName>Value</firstName> 
     <surName>Value</surName> 
     <fullName>Value</fullName> 
     <effDate>Value</effDate> 
    </legalName> 
    </names> 

我有一个看起来像这样的属性列表:

public class Names 
{ 

    [XmlElement("legalName")] 
    public LegalName LegalName { get; set; } 
} 

public class LegalName 
{ 
    [XmlElement("firstName")] 
    public string FirstName { get; set; } 

    [XmlElement("surName")] 
    public string SurName { get; set; } 

    [XmlElement("fullName")] 
    public string FullName { get; set; } 

    [XmlElement("effDate")] 
    public string EffDate { get; set; } 
} 

和逻辑:

foreach (var people in model.Peoples) 
     { 
      exportResult.Persons.Person.Add(new Person 
      { 

       Names = new Names() 
       { 
        LegalName = new LegalName() 
        { 
         FirstName = people.LegalNameFirstName, 
         SurName = people.LegalNameSurName, 
         FullName = people.LegalNameFullName, 
         EffDate = people.LegalNameEffectiveDate 
        } 
       } 
      } 
     } 

    XmlSerializer xsSubmit = new XmlSerializer(typeof(ExportResult)); 
     StringWriter sww = new Utf8StringWrite(); 
     var xml = string.Empty; // Your XML 
     using (XmlWriter writer = XmlWriter.Create(sww, new XmlWriterSettings {Encoding = Encoding.UTF8})) 
     { 
      xsSubmit.Serialize(writer, exportResult); 
      xml = sww.ToString(); 
     } 
     return xml; 

我想知道如何创建这个元素:

<legalName behavior="replace"> 

我应该更改属性类中的XmlElement吗?像这样的:

public class Names 
{ 

[XmlElement("legalName"), XmlAttribute("behavior =\"replace\"")] 
public LegalName LegalName { get; set; } 
} 

我如何使行为=“替换”的legalName元素?

回答

1

要将属性添加为属性,您需要将XmlAttribute属性添加到其父级内的属性(类似于添加子元素)。所以在你的情况下:

public class Names 
{ 
    [XmlElement("legalName")] 
    public LegalName LegalName { get; set; } 
} 

public class LegalName 
{ 
    [XmlElement("firstName")] 
    public string FirstName { get; set; } 

    [XmlElement("surName")] 
    public string SurName { get; set; } 

    [XmlElement("fullName")] 
    public string FullName { get; set; } 

    [XmlElement("effDate")] 
    public string EffDate { get; set; } 

    [XmlAttribute("behavior")] 
    public string Behavior { get; set; } 
}