Sathish
Sathish

Reputation: 1631

Creating xml like the below format

I want to create a XML file in csharp like the below format pls help me with the code

  <MasterEntries>
  <fruit>Apple</fruit>
  <animal>Fox</animal>
  <color>Violet</color>
  </MasterEntries>

Upvotes: 2

Views: 160

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1499790

Well, if you have .NET 3.5 available to you, I'd recommend you use LINQ to XML. For example:

XElement master = new XElement("MasterEntries",
    new XElement("fruit", "Apple"),
    new XElement("animal", "Fox"),
    new XElement("color", "Violet"));

That's about as simple as it gets :)

EDIT: Okay, in .NET 2.0 it's a bit more cumbersome. Something like this:

XmlDocument doc = new XmlDocument();
XmlElement root = doc.CreateElement("MasterEntries");
doc.AppendChild(root);
XmlElement fruit = doc.CreateElement("fruit");
fruit.InnerText = "Apple";
root.AppendChild(fruit);
XmlElement animal = doc.CreateElement("animal");
animal.InnerText = "Fox";
root.AppendChild(animal);
XmlElement color = doc.CreateElement("color");
color.InnerText = "Violet";
root.AppendChild(color);

There may well be simpler ways of doing this, but I don't know them...

Once you've got an XElement/XDocument/XmlDocument, you can call Save to save it to a file.

Upvotes: 8

Related Questions