Note that there are some explanatory texts on larger screens.

plurals
  1. POLiterate LINQ-to-XML: Best practice to deserialize attribute/value to structured variable/value pairs
    text
    copied!<p>I'm wrestling to deserialize the following XML:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;conf name="settings"&gt; &lt;item name="lorem" one="the" two="quick" three="brown" four="fox" five="jumps" six="over" seven="the" eight="lazy" nine="dog" /&gt; &lt;item name="ipsum" one="how" two="many" three="roads" four="must" five="a" six="man" seven="walk" eight="down" nine="?" /&gt; &lt;/conf&gt; </code></pre> <p>hoping to do so in the most elegant and succinct way using LINQ-to-XML, but given that I'm not the smartest kid in town when it comes to nested methods, infered types, generics, et cétera, I thought it'd be a good idea to ask if any of you guys would like to go ahead and show me some LINQ literacy :)</p> <p>Right now for every value I'm doing something like:</p> <pre><code>XDocument config = XDocument.Load("whatever.conf"); var one = from q in config.Descendants("item") select (string)q.Attribute("one"); var two = from q in config.Descendants("item") select (string)q.Attribute("two"); </code></pre> <p>And <em>I do know</em> I'm totally missing the point, not only because I'm repeating myself a lot there but also because that queries only work when there's only one item so, again if you have any comment or suggestion it would be really appreciated. Thanks much in advance!</p> <p><strong>UPDATE:</strong> in case that perhaps the former example wasn't really helpful, here's a more sort of realistic scenario:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;conf name="ftp-settings" freq="daily" time="23:00"&gt; &lt;item name="isis" host="10.10.1.250" user="jdoe" pass="4/cB0kdFGprXR/3oTs8mtw==" file="backup.tar.gz" path="/var/log" /&gt; &lt;item name="seth" host="10.10.2.250" user="jdoe" pass="4/cB0kdFGprXR/3oTs8mtw==" file="backup.tar.gz" path="/var/log" /&gt; &lt;/conf&gt; </code></pre> <p>Therefore for each of those items I'd like to generate variables so I can pass them as parameters for some FTP management method.</p> <p><strong>SOLVED:</strong></p> <p>It was as easy as doing a <strong>foreach</strong>:</p> <pre><code>var elements = from element in xml.Descendants("item") select element; foreach (XElement item in elements) { ftp.DownloadFile( item.Attribute("host").Value, item.Attribute("user").Value, item.Attribute("pass").Value, item.Attribute("file").Value, item.Attribute("path").Value ); } </code></pre>
 

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