Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read node value with XMLTextReader

Tags:

c#

xml

xmlreader

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);
        }
    }
}
like image 557
kentor Avatar asked Feb 04 '26 20:02

kentor


1 Answers

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);
}
like image 137
KV Prajapati Avatar answered Feb 07 '26 10:02

KV Prajapati



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!