开发者

C# - Method for writing xml

I have products in a class that I want to save in a XML file, the products is devided into categoris and I would like to save my produc开发者_运维问答ts in a XML file formatet like below examlple. Products for category 1 writes under category one and products for category 2 under category two.

Hwo can I write a method that dose that? Thanks in advance.

<Categories>
  <Category ID="1">
    <CategoryName>Categoriname1</CategoryName> 
    <Description>drinks, coffees, beers, ales</Description> 
    <Products>
      <Product>
        <ProductName>Coffe</ProductName> 
        <QuantityPerUnit>15 boxes x 60 bags</QuantityPerUnit> 
        <UnitPrice>25</UnitPrice> 
        <UnitsInStock>3</UnitsInStock> 
        <UnitsOnOrder>0</UnitsOnOrder> 
      </Product>
      <Product>
        <ProductName>Chang</ProductName> 
        <QuantityPerUnit>24 - 12 oz bottles</QuantityPerUnit> 
        <UnitPrice>19</UnitPrice> 
        <UnitsInStock>17</UnitsInStock> 
        <UnitsOnOrder>40</UnitsOnOrder> 
      </Product>
    </Products>
  </Category>
  <Category ID="2">
    <CategoryName>Condiments</CategoryName> 
    <Description>spreads, and seasonings</Description> 
    <Products>
      <Product>
        <ProductName>Productname</ProductName> 


You can use LINQ to XML:

http://www.hookedonlinq.com/LINQtoXML5MinuteOverview.ashx


You can use LINQ to XML.

your example would start off like...

  var root = new XElement("Categories",
                    new XElement("Category", 
                          new XAttribute("ID",1),
                          new XElement("CategoryName", "Categoriname1")
                    )
               );     

Your intellisense should help you get the rest


One option is to use LINQ to XML. Assume you have these classes (where I have removed some properties to simplify the example):

class Category {
  public Int32 Id { get; set; }
  public String Name { get; set; }
  public IEnumerable<Product> Products { get; set; }
}

public class Product {
  public String Name { get; set; }
}

You can create some test data:

var categories = new[] {
  new Category {
    Id = 1,
    Name = "Category 1",
    Products = new[] {
      new Product { Name = "Coffee" },
      new Product { Name = "Chang" }
    }
  },
  new Category {
    Id = 2,
    Name = "Condiments",
    Products = new[] {
      new Product { Name = "Product 1" }
    }
  }
};

You can then create an XDocument from the test data:

var xmlDocument = new XDocument(
  new XElement(
    "Categories",
    categories.Select(
      c => new XElement(
        "Category",
        new XAttribute("ID", c.Id),
        new XElement("CategoryName", c.Name),
        new XElement("Products",
          c.Products.Select(
            p => new XElement(
              "Product",
              new XElement("ProductName", p.Name)
            )
          )
        )
      )
    )
  )
);

To save it to a file you can use the Save method:

xmlDocument.Save("Categories.xml");


You need to serialize those classes. Create classes marked with Serializable attribute and use XmlSerializer

example:

http://www.dotnetjohn.com/articles.aspx?articleid=173


You could use the XmlSerializer class or the XmlDocument class or the XDocument class or even the XmlTextWriter class.


You may also like to simply serialise the object(s) that you have. You may write a method like this:

public static bool WriteToXMLFile(string fullFileNameWithPath, Object obj, Type ObjectType)
    {
        TextWriter xr = null;
        try
        {
            XmlSerializer ser = new XmlSerializer(ObjectType);
            xr = new StreamWriter(fullFileNameWithPath);
            ser.Serialize(xr, obj);
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            if(xr != null)
                xr.Close();
        }
        return true;
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜