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 7602287
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 30, 20262026-05-30T23:22:26+00:00 2026-05-30T23:22:26+00:00

I am writing some code to parse an xml file of the following format

  • 0

I am writing some code to parse an xml file of the following format (truncated for simplicity)

<?xml version="1.0" encoding="UTF-8"?>
<ship name="Foo">
 <base_type>Foo</base_type>
 <GFX>fooGFX</GFX>
 ....
</ship>

I am using a dictionary consisting of key pairs of parameter and and xpath to value, and querying this to load all the values into various variables. However, I am noticing that there will be a massive amount of code duplication. In fact, for every value I wish to retrieve, I will have to write another line of almost identical looking code. Here is my code:

class Ship
{
    public Ship()
    {
        paths = new Dictionary<string, string>();
        doc = new XmlDocument();
        //Define path to various elements
        paths.Add("name", "/ship/@name");
        paths.Add("base_type", "/ship/base_type");
        paths.Add("GFX", "/ship/GFX");
    }
    public void LoadFile(string filename)
    {// Loads the file and grabs the parameters
        doc.Load(filename);
        Name = doc.SelectSingleNode(paths["name"]).Value;
        Base_type = doc.SelectSingleNode(paths["base_type"]).Value;
        GFX = doc.SelectSingleNode(paths["GFX"]).Value;
    }

    public Dictionary<string, string> paths; //The XPaths to the various elements, define them in constructor
    public XmlDocument doc;
    public string Name;
    public string Base_type;
    public string GFX;
}

Notice the duplication here:

variable = doc.SelectSingleNode(paths["variable_name"]).value. 

There are going to be many more variables, so this section will be massive.

Is there anyway to simplify this? If this was C++, I would probably try pointers, but I know they are not recommended for use in C#, so is there a similar way?

I would be looking for something that I could give a list of variable names and xpaths, and have the code pull out all the values and load them in the variable in some kind of loop or something. I want to use XPaths because I expect that the format of this file may change periodically.

Any ideas?

Thanks in advance.

EDIT: I would also like to be able to modify this data and save it back. I am not adverse to saving an entire new tree if necessary, but it would be nice to modify the data in place if possible. I don’t need a solution for the modification, but I just need to have this option open.

  • 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-30T23:22:27+00:00Added an answer on May 30, 2026 at 11:22 pm

    One good way to achieve the population of the object is by using XmlSerializer.Deserialize().

    Something like this:

    namespace TestSerialization
    {
        using System;
        using System.IO;
        using System.Xml;
        using System.Xml.Serialization;
    
        public class TestSerialization
        {
            static void Main(string[] args)
            {
                string theXml =
    @"<ship name='Foo'>
     <base_type>Foo</base_type>
     <GFX>fooGFX</GFX>
    </ship>";
                Ship s = Ship.Create(theXml);
    
                // Write out the properties of the object.
                Console.Write(s.Name + "\t" + s.GFX);
            }
        }
    
        [XmlRoot("ship")]
        public class Ship
        {
            public Ship() { }
    
            public static Ship Create(string xmlText)
            {
                // Create an instance of the XmlSerializer specifying type.
                XmlSerializer serializer = new XmlSerializer(typeof(Ship));
    
                StringReader sr = new StringReader(xmlText);
    
                XmlReader xreader = new XmlTextReader(sr);
    
                // Use the Deserialize method to restore the object's state.
                return (Ship)serializer.Deserialize(xreader);
            }
    
            [XmlAttribute("name")]
            public string Name;
    
            [XmlElement("base_type")]
            public string Base_type;
    
            public string GFX;
        }
    }
    

    UPDATE: The OP has added an additional question:

    I would also like to be able to modify this data and save it back. I
    am not adverse to saving an entire new tree if necessary

    Just use the XmlSerializer.Serialize() method.

    Here is a typical example of using it:

      // Create an XmlTextWriter using a FileStream.
      Stream fs = new FileStream(filename, FileMode.Create);
      XmlWriter writer = 
      new XmlTextWriter(fs, Encoding.Unicode);
      // Serialize using the XmlTextWriter.
      serializer.Serialize(writer, yourObject);
      writer.Close();
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Basically I have an XML file that looks like this: <?xml version=1.0 encoding=UTF-8?> <data>
I'm writing some python code that's supposed to parse a CSV file. Calculate the
I am writing some simple code to parse a file and return the number
I'm writing some JavaScript code to parse user-entered functions (for spreadsheet-like functionality). Having parsed
I'm writing some code that handles logging xml data and I would like to
I'm writing some code to parse a string into a double, but this string
I'm writing some C code to parse IEEE 802.11 frames, but I'm stuck trying
I'm writing some code using PacketDotNet and SharpPCap to parse H.225 packets for a
I am writing some code to generate an opml file from a list of
I'm writing some code to parse forwarded emails. What I'm not sure is if

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.