Search code examples
c#xmlxmlreader

Read node value with XMLTextReader


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);
        }
    }
}

Solution

  • 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);
    }