Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Xml Serialization works nicely. You use attributes to configure it. </p> <p>You can conditionally include elements. </p> <p>EDIT: <strong>I've updated the code to reflect your updated question.</strong></p> <pre><code>[XmlRoot("pdata")] // this element name used if serialized to doc root public class PersonalData { [XmlElement] // with no name here, elt name = prop name public string Name; [XmlElement] // with no name here, elt name = prop name public int Age; [XmlElement("xaddr")] // override xml element name public AddressData Address; [XmlElement] public Under18Info Other {get; set;} // serialize the above element, only if Age &lt; 18 [XmlIgnore] // do not serialize the *Specified" property in any case private bool OtherSpecified { get { return Age &lt; 18; } } } public class AddressData { [XmlIgnore] // do not serialize (see Composite prop) public string Line1 { get; set;} [XmlAttribute("city")] // serialize as an attribute on the parent public string City {get; set;} [XmlIgnore] // do not serialize public string Postcode {get; set;} [XmlText] // serialize as the Text node public string Composite { get { return Line1 + ", " + Postcode; } set { var split = value.Split(','); Line1 = split[0]; Postcode= split[1]; } } } </code></pre> <p>Then, to serialize an instance of that to a string, for example: </p> <pre><code>var pdata = new PersonalData { Name = "Gordon Brown", Age = 57, Address = new AddressData { Line1 = "10 Downing St.", Postcode = "1QR 3E4", City = "London" } }; var ns= new System.Xml.Serialization.XmlSerializerNamespaces(); ns.Add( "", ""); var s1 = new XmlSerializer(typeof(PersonalData)); var builder = new System.Text.StringBuilder(); var xmlws = new System.Xml.XmlWriterSettings { OmitXmlDeclaration = true, Indent= true }; using ( var writer = System.Xml.XmlWriter.Create(builder, xmlws)) { s1.Serialize(writer, pdata, ns); } string xml = builder.ToString(); </code></pre> <p>Results:</p> <pre><code>&lt;pdata&gt; &lt;Name&gt;Gordon Brown&lt;/Name&gt; &lt;Age&gt;57&lt;/Age&gt; &lt;xaddr city="London"&gt;10 Downing St., 1QR 3E4&lt;/xaddr&gt; &lt;/pdata&gt; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload