Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#/XML: 'System.Xml.XmlDocument' does not contain a definition for 'Descendants'

Tags:

c#

definition

xml

I just received an error a while ago from this code:

private void ShowXMLDatatoRTB() {
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("XMLFile.xml");

var persons = from person in xmlDoc.Descendants("Person")
        select new
            {
                Name = person.Element("Name").Value,
                    City = person.Element("City").Value,
                Age = person.Element("Age").Value,
            };

richTextBox1.Text = "";
foreach (var person in persons)
{
    richTextBox1.Text = richTextBox1.Text + "Name: " + person.Name + "\n";
            richTextBox1.Text = richTextBox1.Text + "City: " + person.City + "\n";
            richTextBox1.Text = richTextBox1.Text + "Age: " + person.Age + "\n\n";
    }

if (richTextBox1.Text == "")
            richTextBox1.Text = "No Results."; }

Am I missing something?

like image 287
abramlimpin Avatar asked Nov 28 '22 23:11

abramlimpin


2 Answers

You just need to switch from XmlDocument to XDocument.

like image 130
Jay Allard Avatar answered Nov 30 '22 12:11

Jay Allard


You are trying to use LINQ to SQL but actually using the old school DOM API. You need to add references to System.XML and System.Xml.Linq and use XDocument, not XmlDocument.

like image 30
Igor Zevaka Avatar answered Nov 30 '22 12:11

Igor Zevaka