I'm trying to store and print the value between <name></name> tags of, atleast, the first <item></item> element, but I can't "find", or "get to", the value of <name></name>.

(please explain your scenario more clearly...)

I plan on taking the extracted name value and converting it(all lowercase and add underscore for spaces between words) so that I can use it to search for an image file name within "images" folder.

If match is found - grab the file path to the image file, store it inside a variable and then create <image></image> within the current <item></item> element and paste the file path between the tags. Repeat that for another 999 items. If some of the items' name doesn't match any image file names - then create a log text file and store the names of the items that didn't get the match.

XML structure:

<items>
 <item>
  <name>Name1</name>
  <price>Price1</price>
  <description>Description1</description>
 </item>
 <item>
  <name>Name2</name>
  <price>Price2</price>
  <description>Description2</description>
 </item>
</items>

Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;


    namespace myXmlParser
    {
        class Program
        {
            static void Main(string[] args)
            {
                XmlTextReader reader = new XmlTextReader("C:\\items_data.xml");
                while (reader.Read())
                {
                    switch (reader.NodeType)
                    {
                        case XmlNodeType.Element: // The node is an element.
                            reader.MoveToElement();
                            Console.WriteLine(reader.Name);
                            break;
                        //case XmlNodeType.Text: //Display the text in each element.
                        //    Console.WriteLine(reader.Value);
                        //    break;
                        //case XmlNodeType.EndElement: //Display the end of the element.
                        //    Console.Write("</" + reader.Name);
                        //    Console.WriteLine(">");
                        //    break;
                    }

                }
                Console.ReadKey();

            }// main
        }// class
    }// namespace
2

There are 2 answers

0
Jony Adamit On BEST ANSWER

Try reader.ReadContentAsString when reader.Name == "name".
Since you plan on editing the XML later, you might as well use XmlDocument, and apply the XPath you were suggested earlier.

1
L.B On

Linq2Xml is easier to use

XDocument xDoc = XDocument.Load("C:\\items_data.xml");
var names = xDoc.Descendants("name")
    .Select(x => x.Value)
    .ToArray();

-

 xDoc.Descendants("name")
    .Where(x => x.Value == "Name1")
    .First()
    .Parent.Add(new XElement("image", "path of the image"));