Home   Cover Cover Cover Cover
 

Erzeugung einer XML-Datei

A09.cs
/* Creation of an XML file from a list of articles
   This example creates a list of articles and transforms it into
   an XML file, where the article code and the article price
   are attributes of an article, and the article name is a subelement
   of the article.
------------------------------------------------------------*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using System.IO;

class Article {  // article
  public int Code { get; set; }     // article code
  public string Name { get; set; }  // article name
  public int Price { get; set; }    // article price
}

public class A9 {
  
  public static void Main() {
    var articles = new List< Article > {
      new Article {Code = 101, Name = "USB-Stick 4GB", Price = 9},
      new Article {Code = 102, Name = "USB-Stick 8GB", Price = 15},
      new Article {Code = 103, Name = "USB-Stick 16GB", Price = 20},
      new Article {Code = 111, Name = "Harddisk 200GB", Price = 55},
      new Article {Code = 112, Name = "Harddisk 500GB", Price = 120},
      new Article {Code = 121, Name = "WLAN-Router 150N", Price = 39},
      new Article {Code = 122, Name = "WLAN-Router 54G", Price = 45},
      new Article {Code = 123, Name = "ADSL-Modem 108MBPS", Price = 115},
      new Article {Code = 123, Name = "ADSL-Modem 54MBPS", Price = 85}
    };
    
    XElement root = new XElement("articles", 
      from article in articles
      orderby article.Code
      select new XElement("article",
        new XAttribute("code", article.Code),
        new XAttribute("price", article.Price),
        new XElement("name", article.Name)
      )
    );
    
    FileStream s = new FileStream("articles.xml", FileMode.Create);
    StreamWriter w = new StreamWriter(s);
    w.WriteLine(root);
    w.Close();
    s.Close();
  }
}