2

I want insert each element from an array add them to a XML tree.

List<String> list = {"abc","cba","bca"};  
NameList.Add(new XElement("movie", new XElement("title", this.textBox1.Text), new XElement("genre",list)));

This statement just create stuff like this:

<movie>
<title>smoething</title>
<genre>abccbabca</genre>
</movie>

I want create like this:

<movie>
<title>smoething</title>
<genre>abc</genre>
<genre>cba</genre>
<genre>bca</genre>
</movie>

2 Answers 2

4

There is a very simple solution using LINQ:

List<String> list = {"abc","cba","bca"}; 
NameList.Add(new XElement("movie", new XElement("title", this.textBox1.Text), list.Select(l => new XElement("genre", l))));
Sign up to request clarification or add additional context in comments.

1 Comment

Cool! It is just awesome!
2

using for loop could be a way

        var strList = new List<string> {"abc", "cba", "bca"};
        var xml = new XmlDocument();
        var root = xml.AppendChild(xml.CreateElement("Movie"));
        root.AppendChild(xml.CreateElement("Title")).InnerText = "somthing";

        foreach (var str in strList)
        {
            root.AppendChild(xml.CreateElement("Genre")).InnerText = str;
        }

        MessageBox.Show(xml.OuterXml);

Comments

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.