2

I want to take an XML file and put its data into an array in C#

My code:

XmlDocument XMLDoc = new XmlDocument();
XMLDoc.Load("C:/Scripts/example.xml");
string[] bans = XMLDoc.Descendants("ban").Select(element => element.Value).ToArray();

But, I keep getting this error:

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

Here is my xml file if its relevant:

<championSelect>
    <blue>
        <ban order="1">Darius</ban>
        <ban order="3">Elise</ban>
        <ban order="5">Twisted Fate</ban>
        <pick order="1">Gragas</pick>
        <pick order="4">Shen</pick>
        <pick order="5">Shyvanna</pick>
    </blue>
    <red>
        <ban order="2">Jayce</ban>
        <ban order="4">Zac</ban>
        <ban order="6">Thresh</ban>
        <pick order="2">Draven</pick>
        <pick order="3">Ryze</pick>
    </red>
</championSelect>

I think it has to do with the .Descendants but I can't say for certain. I've tried a lot of the other solutions here on stack overflow to no avail. I welcome another approach if neccessary

3 Answers 3

3

Your LINQ looks fine, however you're using an XmlDocument (from the System.Xml namespace). For the LINQ to work you want to use an XDocument instead, which is part of the System.Xml.Linq namespace:

var doc = XDocument.Load("C:/Scripts/example.xml");
string[] bans = doc.Descendants("ban")
                   .Select(element => element.Value)
                   .ToArray();
Sign up to request clarification or add additional context in comments.

Comments

0

Looks like you're missing your LINQ reference, perhaps? Try adding

Using System.Xml.Linq;  

2 Comments

unfortunately, I am already using System.Xml.Linq; as well as System.Linq; thanks though
Perhaps you mean to be using XDocuments instead of XmlDocument
0

You are getting that error because you should be using the XDocument class, which is part of the System.XML.Linq namesapace

http://msdn.microsoft.com/en-us/library/system.xml.linq.xdocument.aspx

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.