1
votes

I try to get the value of a node but it always returns me an empty String. As far as I read I have to access the node first in order to read it but I haven't found an example/the syntax to do it. My XMLNode name is "BuyNowPrice" and is multiple times inside of my XML File.

using (XmlReader xmlReader = XmlTextReader.Create(@"C:\benatia.xml"))
{
    while (xmlReader.Read())
    {
        if (xmlReader.IsStartElement())
        {
            if (xmlReader.Name == "BuyNowPrice") Console.WriteLine(xmlReader.Name + ": " + xmlReader.Value);
        }
    }
}
1
FYI, it would be better practice to use XmlReader.Create. XmlTextReader.Create is actually the same thing. - John Saunders
Side note: readers API is probably the hardest one to work with among .Net XML APIs. Unless you looking for 10Mb+ files LINQ-to-XML may be easier to deal with (and definitely way more samples). - Alexei Levenkov

1 Answers

8
votes

In order to read the content of an element, you need to call ReadElementContentXxxxx() method.

if (xmlReader.IsStartElement())
 {
 if (xmlReader.Name == "BuyNowPrice") 
      Console.WriteLine(xmlReader.Name + ": " 
              + xmlReader.ReadElementContentAsString());
}

LinqToXml

XDocument xml = XDocument.Load(file);
foreach(var e in xml.Descendants("BuyNowPrice"))
{
 Console.WriteLine(e.Name + " : " + (string)e);
}