创建具有<元素行为= "replace">在c#
本文关键字:quot replace 元素 创建 | 更新日期: 2023-09-27 18:06:55
我试图重新创建一个xml,其结果应该看起来像这样:
<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; }
}
如何使用behavior="replace"来创建legalName元素
要将属性添加为属性,您需要将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; }
}