1

My purpose is to make a program that creates a new file destination that takes some values from another file. The XML file:

 <?xml version="1.0"?>
  <house>
  <chairs count="3">
  <chairs>a</chairs>
  <chairs>b</chairs>
  <chairs>c</chairs>
  </chairs>
 </house>

What I've done:

 static void Main(string[] args)
    {
       using (XmlReader reader = XmlReader.Create("file.xml"))
        {
            while (reader.Read())
            {
                if (reader.IsStartElement())
                {
                    switch (reader.Name)
                    {

                        case "chairs":

                            if (reader.Read())
                            {
                                string l;
                                l = reader.Value.Trim();
                                //(*)
                            }
                            break;
                    }
                }
            }
        }

  // (**)f = l + " ";

If I write at the * line :

 Console.WriteLine(l), it will print me:

 a
 b
 c 

But if I delete the (*) and I uncomment the (**), in the new created file it only shows c because I think it overrides the a and b because of concatenation. It is possible to take all the values a,b,c and to write in the file, not only the last value?

2 Answers2

1

There are number of ways you can do that.

but one of the most convinient ways of working with XMLs (when you know schema in advance) is to use XSD.exe and generate classes for your schema, and then just deserialize your xml to classes and work with C# classes.

Community
  • 1
  • 1
vittore
  • 17,449
  • 6
  • 44
  • 82
0

Try this:

static void Main(string[] args)
{
   List<string> strings = new List<string>();
   using (XmlReader reader = XmlReader.Create("file.xml"))
    {
        while (reader.Read())
        {
            if (reader.IsStartElement())
            {
                switch (reader.Name)
                {

                    case "chairs":

                        if (reader.Read())
                        {
                            strings.Add(reader.Value.Trim());
                        }
                        break;
                }
            }
        }
    }

This way the list strings will have all the nodes in it and can be used as a collection. You could concatenate if you wanted but the assignment in the initial code would suggest you are merely overwriting the value each time.

JB King
  • 11,860
  • 4
  • 38
  • 49