CSharper
CSharper

Reputation: 779

How to generate an XML file dynamically using XDocument?

As I wrote in the subject itself , how can I do that?
Note that solution like this are not appropriate as I want to create child nodes dynamically through running..

new XDocument(
    new XElement("root", 
        new XElement("someNode", "someValue")    
    )
)
.Save("foo.xml");

I guess this was clear enough the first time but I will write it again:

I need to be able to add child nodes to given parent node while running, in the current syntax I've written this is static generated xml which doesn't contribute me at all because all is known in advance, which is not as my case.

How would you do it with Xdocument, is there away?

Upvotes: 3

Views: 16909

Answers (2)

OpenMinded
OpenMinded

Reputation: 486

If a document has a defined structure and should be filled with dynamic data, you can go like this:

// Setup base structure:
var doc = new XDocument(root);
var root = new XElement("items");
doc.Add(root);

// Retrieve some runtime data:
var data = new[] { 1, 2, 3, 4, 5 };

// Generate the rest of the document based on runtime data:
root.Add(data.Select(x => new XElement("item", x)));

Upvotes: 9

Nipun Ambastha
Nipun Ambastha

Reputation: 2573

Very simple

Please update your code accordingly

XmlDocument xml = new XmlDocument();
XmlElement root = xml.CreateElement("children");
xml.AppendChild(root);

XmlComment comment = xml.CreateComment("Children below...");
root.AppendChild(comment);

for(int i = 1; i < 10; i++)
{
    XmlElement child = xml.CreateElement("child");
    child.SetAttribute("age", i.ToString());
    root.AppendChild(child);
}
string s = xml.OuterXml;

Upvotes: 6

Related Questions