2

I'm trying to write a code to convert a xml file into a datatable. I'm getting this below error

System.Xml.Linq.XDocument' does not contain a definition for 'DocumentNode' and no extension method 'DocumentNode' accepting a first argument of type 'System.Xml.Linq.XDocument' could be found (are you missing a using directive or an assembly reference?)

What am I missing?

Below is my code

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

using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main()
        {



            var xdoc = System.Xml.Linq.XDocument.Load(filename);
            System.Xml.XmlElement xelRoot = xdoc.DocumentElement;
            System.Xml.XmlNodeList xList = xelRoot.SelectNodes("/rulebase/security/rules/entry");

            int x = 0;
            int y = 0;
            string[] ColumnArray = new string[25];
            string[] RowArray = new string[25];


            foreach (System.Xml.XmlNode pNode in xList)
            {



                if (pNode.ChildNodes.Count = 0)
                {

                }
                else
                {
                    string val1 = "";
                    string nodeVal = "";

                    string nodeName = pNode.name;
                    foreach (System.Xml.XmlNode childNode in pNode.ChildNodes)
                    {
                        val1 = val1 + childNode.value + ", ";
                    }
                    val1 = val1 + " ,";
                    nodeVal = val1.substring(0, val1.length - 3);

                    ColumnArray[x] = nodeName;
                    RowArray[y] = nodeVal;
                    x++;
                    y++;

                }
            }

            System.Data.DataTable table1 = new System.Data.DataTable("entry");

            foreach (string s in ColumnArray)
            {
                table1.Columns.Add(s);
            }

            System.Data.DataRow row;
            row = table1.LoadDataRow(RowArray, true);
        }

    }
}
user4479980
  • 149
  • 1
  • 2
  • 8
  • 2
    You are mixing the X* and Xml* families of classes. That won't work. .NET has (at least) 2 distinct APIs for dealing with Xml, pick one. My choice would be the Linq based one. – H H Jun 22 '15 at 21:34
  • Got it! Thanks @HenkHolterman – user4479980 Jun 23 '15 at 20:32

1 Answers1

0

(Initially I didn't understand the comment under the question, so here some details)

The older System.Xml.XmlDocument has DocumentElement (this is being used in the code ... I don't know where the DocumentNode mentioned in the question comes from).

System.Xml.Linq.XDocument

  • is the newer LINQ to XML class
  • which does not have DocumentElement.
  • e.g. use xdoc.Root.Name to get the name of the root element

For more info XMlDocument vs XDocument

Community
  • 1
  • 1
robor
  • 2,969
  • 2
  • 31
  • 48