Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 680275
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 14, 20262026-05-14T01:21:15+00:00 2026-05-14T01:21:15+00:00

I’m having difficulty doing this seemingly simple task. I want to load XML files

  • 0

I’m having difficulty doing this seemingly simple task. I want to load XML files with the same ease of loading art assets:

        content  = new ContentManager(Services);
        content.RootDirectory = "Content";
        Texture2d background = content.Load<Texture2D>("images\\ice");

I’m not sure how to do this. This tutorial seems helpful, but how do I get a StorageDevice instance?

I do have something working now, but it feels pretty hacky:

public IDictionary<string, string> Get(string typeName)
        {
            IDictionary<String, String> result = new Dictionary<String, String>();
            xmlReader.Read(); // get past the XML declaration

            string element = null;
            string text = null;

            while (xmlReader.Read())
            {

                switch (xmlReader.NodeType)
                {
                    case XmlNodeType.Element:
                        element = xmlReader.Name;
                        break;
                    case XmlNodeType.Text:
                        text = xmlReader.Value;
                        break;
                }

                if (text != null && element != null)
                {
                    result[element] = text;
                    text = null;
                    element = null;
                }

            }
            return result;
        }

I apply this to the following XML file:

<?xml version="1.0" encoding="utf-8" ?>
<zombies>
  <zombie>
    <health>100</health>
    <positionX>23</positionX>
    <positionY>12</positionY>
    <speed>2</speed>
  </zombie>
</zombies>

And it is able to pass this unit test:

    internal virtual IPersistentState CreateIPersistentState(string fullpath)
    {
        IPersistentState target = new ReadWriteXML(File.Open(fullpath, FileMode.Open));
        return target;
    }

    /// <summary>
    ///A test for Get with one zombie.
    ///</summary>
    //[TestMethod()]
    public void SimpleGetTest()
    {
        string fullPath = "C:\\pathTo\\Data\\SavedZombies.xml";
        IPersistentState target = CreateIPersistentState(fullPath);
        string typeName = "zombie"; 

        IDictionary<string, string> expected = new Dictionary<string, string>();
        expected["health"] = "100";
        expected["positionX"] = "23";
        expected["positionY"] = "12";
        expected["speed"] = "2";

        IDictionary<string, string> actual = target.Get(typeName);

        foreach (KeyValuePair<string, string> entry in expected)
        {
            Assert.AreEqual(entry.Value, expected[entry.Key]);
        }
    }

Downsides to the current approach: file loading is done poorly, and matching keys to values seems like it’s way more effort than necessary. Also, I suspect this approach would fall apart with more than one entry in the XML.

I can’t imagine that this is the optimal implementation.

UPDATE: Following the advice of @Peter Lillevold, I’ve changed this a bit:

    public IDictionary<string, string> Get(string typeName)
    {
        IDictionary<String, String> result = new Dictionary<String, String>();

        IEnumerable<XElement> zombieValues = root.Element(@typeName).Elements();

        //result["health"] = zombie.Element("health").ToString();

        IDictionary<string, XElement> nameToElement = zombieValues.ToDictionary(element => element.Name.ToString());

        foreach (KeyValuePair<string, XElement> entry in nameToElement)
        {
            result[entry.Key] = entry.Value.FirstNode.ToString();
        }

        return result;
    }

    public ReadWriteXML(string uri)
    {
        root = XElement.Load(uri);
    }

    internal virtual IPersistentState CreateIPersistentState(string fullpath)
    {
        return new ReadWriteXML(fullpath);
    }

    /// <summary>
    ///A test for Get with one zombie.
    ///</summary>
    [TestMethod()]
    public void SimpleGetTest()
    {
        IPersistentState target = CreateIPersistentState("../../../path/Data/SavedZombies.xml");
        string typeName = "zombie"; 

        IDictionary<string, string> expected = new Dictionary<string, string>();
        expected["health"] = "100";
        expected["positionX"] = "23";
        expected["positionY"] = "12";
        expected["speed"] = "2";

        IDictionary<string, string> actual = target.Get(typeName);

        foreach (KeyValuePair<string, string> entry in expected)
        {
            Assert.AreEqual(entry.Value, actual[entry.Key]);
        }
    }

The loading is still pretty crappy, and somehow I wasn’t able to get the one-line ToDictionary to work with those two lambdas. I had to resort to that foreach loop. What am I doing wrong there?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-14T01:21:15+00:00Added an answer on May 14, 2026 at 1:21 am

    There is also the new and shiny XElement (which sports Linq to XML). This sample will load an xml file, look up the zombie and dump the values into a dictionary:

    var doc = XElement.Load("filename");
    var zombieValues = doc.Element("zombie").Elements();
    var zombieDictionary = 
        zombieValues.ToDictionary(
            element => element.Name.ToString(), 
            element => element.Value);
    

    If you’d rather pick each value explicitly (and use casting for automatically converting into proper value types) you can do:

    var zombie = doc.Element("zombie");
    var health = (int)zombie.Element("health");
    var positionX = (int)zombie.Element("positionX");
    var positionY = (int)zombie.Element("positionY");
    var speed = (int)zombie.Element("speed");
    

    Update: fixing some typos and cleaning up a bit, your Get method should look like this:

    public IDictionary<string, string> Get(string typeName)
    {
        var zombie = root.Element(typeName);
        return zombie.Elements()
              .ToDictionary(
                      element => element.Name.ToString(),
                      element => element.Value);
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 368k
  • Answers 368k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer As David F figured out but I did not grok,… May 14, 2026 at 6:03 pm
  • Editorial Team
    Editorial Team added an answer If you use encrypt() with no salt, a random salt… May 14, 2026 at 6:03 pm
  • Editorial Team
    Editorial Team added an answer The JDBC API was designed for performance. Remember that it… May 14, 2026 at 6:03 pm

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.