Jasinski Technical Wiki

Navigation

Home Page
Index
All Pages

Quick Search
»
Advanced Search »

Contributor Links

Create a new Page
Administration
File Management
Login/Logout
Your Profile

Other Wiki Sections

Software

PoweredBy

Page History: Building XML Programmatically

Compare Page Revisions



« Older Revision - Back to Page History - Current Revision


Page Revision: Tue, Aug 09, 2011, 7:02 PM


public class Person
{
    public string Address { get; set; }
    public string Name { get; set; }
}

public static string ToXml(List<Person> people)
{
    var sw = new System.IO.StringWriter();
    var xw = new System.Xml.XmlTextWriter(sw);
    xw.Formatting = Formatting.Indented;
    xw.Indentation = 4;

    xw.WriteStartElement("xml");
    var oldAddress = "";
    var firstPass = true;

    foreach (var person in people)
    {
        if (!firstPass && person.Address != oldAddress)
            xw.WriteEndElement(); // </address>

        if (firstPass || person.Address != oldAddress)
        {
            xw.WriteStartElement("address");
            xw.WriteAttributeString("id", person.Address);
        }

        xw.WriteStartElement("name");
        xw.WriteAttributeString("id", person.Name);
        xw.WriteEndElement(); // </name>

        firstPass = false;
        oldAddress = person.Address;
    }
    xw.WriteEndElement(); // </address>
    xw.WriteEndElement(); // </xml>
    return sw.ToString();
}

ScrewTurn Wiki version 3.0.1.400. Some of the icons created by FamFamFam. Except where noted, all contents Copyright © 1999-2024, Patrick Jasinski.