0

I'm trying to load an XML file into a ListView, however, every time I select the file, I get an error which says

System.Xml.Linq.XContainer.Element(…) returned null

This is my code:

XDocument doc = XDocument.Load(typesXML);
IEnumerable<XElement> serverElements = doc.Descendants("type");

foreach (XElement serverElement in serverElements)
{
    ListViewItem item = new ListViewItem(new string[]
    {
        serverElement.Element("nominal").Value,
        serverElement.Element("lifetime").Value,
        serverElement.Element("restock").Value,
        serverElement.Element("min").Value,
        serverElement.Element("quantmin").Value,
        serverElement.Element("quantmax").Value,
        serverElement.Element("cost").Value
    });

    listView1.Items.Add(item);
}

XML:

<types>
    <type name="ACOGOptic">
        <nominal>15</nominal>
        <lifetime>7200</lifetime>
        <restock>1800</restock>
        <min>8</min>
        <quantmin>-1</quantmin>
        <quantmax>-1</quantmax>
        <cost>100</cost>
        <flags count_in_cargo="0" count_in_hoarder="0" count_in_map="1" count_in_player="0" crafted="0" deloot="0"/>
        <category name="weapons"/>
        <usage name="Military"/>
    </type>
</types>

Also, how would I go when I also want the tag "name" from "type" load into my ListView?

It worked with using DataSet, but I want to use it like this.

CunnertA
  • 165
  • 2
  • 12
  • Is this your complete XML? – GSerg Jun 14 '20 at 11:23
  • I have edited my post and added the whole XML (there are lot of more but its very long, so I'm not gonna post it here) – CunnertA Jun 14 '20 at 11:26
  • `there are lot of more ` - do all them have all the `nominal`, `lifetime` etc child elements? – GSerg Jun 14 '20 at 11:28
  • Yes they do have all the same elements. – CunnertA Jun 14 '20 at 11:30
  • Then you cannot be having your problem. – GSerg Jun 14 '20 at 11:33
  • If the element doesn't exist you will get an error using value. So change make following changes From : serverElement.Element("nominal").Value, To : (string)serverElement.Element("nominal"), – jdweng Jun 14 '20 at 11:51
  • My fault, some values indeed doesnt exist. Your solution worked. You can post it as an answer so I can checkmark it :) – CunnertA Jun 14 '20 at 11:55
  • @jdweng how would I read the other elements like "usage" or "category", these are closed tags, so I would need the "name" attribute", I have tried ```(string)item.Element("category").Attribute("name")``` but that doesnt work. – CunnertA Jun 14 '20 at 12:23
  • Possible duplicate of [Checking for null values if element does not exist](https://stackoverflow.com/questions/46103971/checking-for-null-values-if-element-does-not-exist) – GSerg Jun 14 '20 at 12:27
  • I have actually found the solution which is probably the same as yours @GSerg ``` item.Element("cost")?.Value, item.Element("category")?.Attribute("name").Value ``` – CunnertA Jun 14 '20 at 12:38

0 Answers0