3

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?

2
  • 1
    Have you tried anything? Commented May 17, 2013 at 13:17
  • I've tried therfore I'm asking, there are so much xml methods that it making me xonfused: xmlWriter Xpath Xdocument xmlDocument Commented May 17, 2013 at 13:53

2 Answers 2

9

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)));
Sign up to request clarification or add additional context in comments.

Comments

6

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;

6 Comments

What is dynamic about this?
new XElement("someNode", "someValue") As its not known he need to atleast frame out method to implement dynamic value
That line doesn't even exist in your code. And you don't even use XDocument, which is what OP is looking for. I don't think you understand what the word "dynamic" means. Nothing you've put so far is dynamic.
Agreed, but it can be done like this too. The values had to be replaced, contents need to be changed.
Your solution still has nothing dynamic about it. It doesn't even accept any input or values. The entire solution is static. Replacing string values in that solution STILL is not dynamic.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.