Note that there are some explanatory texts on larger screens.

plurals
  1. POReduce Code Duplication when Searching for values in XML with XPath
    text
    copied!<p>I am writing some code to parse an xml file of the following format (truncated for simplicity)</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;ship name="Foo"&gt; &lt;base_type&gt;Foo&lt;/base_type&gt; &lt;GFX&gt;fooGFX&lt;/GFX&gt; .... &lt;/ship&gt; </code></pre> <p>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:</p> <pre><code>class Ship { public Ship() { paths = new Dictionary&lt;string, string&gt;(); 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&lt;string, string&gt; paths; //The XPaths to the various elements, define them in constructor public XmlDocument doc; public string Name; public string Base_type; public string GFX; } </code></pre> <p>Notice the duplication here:</p> <pre><code>variable = doc.SelectSingleNode(paths["variable_name"]).value. </code></pre> <p>There are going to be many more variables, so this section will be massive.</p> <p>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?</p> <p>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.</p> <p>Any ideas?</p> <p>Thanks in advance.</p> <p>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.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload