我试图重新创建一个结果应该如下所示的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 =&#34生成一个legalName元素;替换&#34; ?
答案 0 :(得分: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; }
}