0

I am very new to C# but attempting to make an app to parse a simple XML file like shown below and populate the data inside a multi-column ListView.

<mods>
<mod Name="mod1.zip" sha1="508ed8f5fcd7d323d9296acad76f1183b810f62a"/>
<mod Name="mod2.zip" sha1="669d8d09d297a9724fe1d1d676ac5f5a8ff10277"/>
</mods>

Here is the code I'm trying to work from but it isn't populating the ListView like I'd expect it to..

modList.View = View.Details;
modList.Columns.Add("Name", 650);
modList.Columns.Add("Status", 111, HorizontalAlignment.Center);

XElement root = XElement.Load("https://website.com/modlist.xml");
var mods = from subject in root.Descendants()
            where subject.Name.LocalName.Contains("Mod")
            select new
            {
                Name = subject.Element("Name").Value,
                Hash = subject.Element("Hash").Value,
            };

foreach (var mod in mods)
{
    modList.Items.Add(new ListViewItem(new string[]
        {
            mod.Name,
            mod.Hash
        }));

}
2
  • 2
    You're looking for Mod elements, but they're all mod elements. You're also looking for elements called Name and Hash, but they're actually attributes called Name and sha1. (It's not clear why you're using Contains rather than just using root.Descendants("mod") either.) Commented Apr 28, 2020 at 6:37
  • your XML element doesnt have an attribute called Hash, instead they are sha1, sha2 per your above code snippet. That could be reason why it wont be finding and populating the Hash property. Commented Apr 28, 2020 at 6:38

1 Answer 1

2

You can get all mods using Descendants("mod"). And the attribute using Attribute("Name")

var mods = from ele in xDoc.Descendants("mod")
                    select new
                    {
                        Name = (string)ele.Attribute("Name"),
                        Hash = (string)ele.Attribute("sha1")
                    };

Demo

You can use Attributes() to list all the attributes. If you have to handles Hash beeing in a SHA-1, SHA-2 , or SHA-256 attribute

Sign up to request clarification or add additional context in comments.

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.