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

Building XML Programmatically

RSS
Modified on Thu, Aug 11, 2011, 12:38 PM by Administrator Categorized as XML, XSL, and XPath
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 = System.Xml.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-2018, Patrick Jasinski.