-2

Guys i need to hard Code my XML string list data and then display it as the below out put in a console window!

<Photos>
    <Photo> p1.jpg </Photo>
        <Photo> p2.jpg </Photo>
    <Photo> p3.jpg </Photo>
    <Photo> p4.jpg </Photo>
    <Photo> p5.jpg </Photo>
</Photos>

This what i have done so far!

namespace ConsoleApplication17
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> list = new List<string>();
            list.Add("p1.jpg");
            list.Add("p2.jpg");
            list.Add("p3.jpg");
        }
    }
}

Appreciate any help!

MPelletier
  • 16,256
  • 15
  • 86
  • 137
Drek John
  • 85
  • 6
  • 3
    What you have done does not appear to be XML related at all... what exactly are you having trouble with? WHich part? – Simon Whitehead Jul 31 '13 at 04:16
  • 1
    You can use a StringBuilder or if you can do a nice XMLSerialization if you take the time to search for that (it's very useful to learn). Or if it's hardcoded, as you say, just make it a big const string. – MPelletier Jul 31 '13 at 04:19
  • @SimonWhitehead i need to add data to this string list and display it as above! Please dont down Rate the question, i want be able to ask questions in future! – Drek John Jul 31 '13 at 04:23
  • I guess the OP wants to generate XML from the string list. You can take a look at how to [construct XML](http://stackoverflow.com/questions/284324/what-is-the-best-way-to-build-xml-in-c-sharp-code) on the fly first. – Fung Jul 31 '13 at 04:28
  • 1
    `List list = new List(); list.Add("p1.jpg"); list.Add("p2.jpg"); list.Add("p3.jpg"); var xElement = new XElement ("Photos"); foreach (var item in list) { xElement.Add(new XElement ("Photo", item)); } Console.WriteLine(xElement);` – Damith Jul 31 '13 at 04:29

1 Answers1

0

You want to convert your xml to a List<string>()?

In that case, using LINQ to XML:

var str = @"<Photos>
    <Photo> p1.jpg </Photo>
    <Photo> p2.jpg </Photo>
    <Photo> p3.jpg </Photo>
    <Photo> p4.jpg </Photo>
    <Photo> p5.jpg </Photo>
    </Photos>";

XDocument.Parse(str)
    .Descendants("Photo")
    .Select (s => s.Value)
    .ToList<string>();

Alternatively, If you want to create XML:

var xPhotos = new XElement("Photos");
for (var x = 1; x < 6; x++) {
    xPhotos.Add(new XElement("Photo", "p" + x + ".jpg"));
}
var xdoc = new XDocument(xPhotos);

The above assumes you have a set limit of numbers for your jpg names.


OR, if you want to create xml from the List<string>() that you already have:

// your existing code:
List<string> list = new List<string>();
            list.Add("p1.jpg");
            list.Add("p2.jpg");
            list.Add("p3.jpg");

// to xml:
var xPhotos = new XElement("Photos");
foreach(string x in list)
    xPhotos.Add(new XElement("Photo", x));
var xdoc = new XDocument(xPhotos);
mnsr
  • 12,337
  • 4
  • 53
  • 79