Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Much as I like using LINQ and <code>XDocument</code>, this is a case where XPath is simpler.</p> <p>Given your XML, this XPath finds all of the <code>VIPair</code> elements under a <code>Pin</code> element with a given <code>Number</code> and under a <code>Curve</code> element with a given <code>Type</code>:</p> <pre><code>/Document/Device/Pins/Pin[Number='A1']/Curves/Curve[Type='PreStress']/VIPairs/VIPair </code></pre> <p>Using an <code>XmlDocument</code>, the code to get your three voltage and current values would look like this:</p> <pre><code>string number = "A1"; string type = "PreStress" string xpath = string.Format( "/Document/Device/Pins/Pin[Number='{0}']/Curves/Curve[Type='{1}']/VIPairs/VIPair", number, type); foreach (XmlElement viPair in doc.SelectNodes(xpath)) { string current = viPair.SelectSingleNode("Current").Value; string voltage = viPair.SelectSingleNode("Voltage").Value; } </code></pre> <p>Using an XDocument, the code would be:</p> <pre><code>var values = doc.XPathSelectElements(xpath) .Select(x =&gt; new { Voltage = x.Element("Voltage").Value(), Current = x.Element("Current").Value() }); </code></pre> <p>Unless your document's been previously validated against a schema, you may want to make the last node test in the XPath <code>VIPair[Current and Voltage]</code>, so that the code doesn't fail if there's a <code>VIPair</code> element that's missing one of those child elements. (Alternatively, you might actually <em>want</em> the code to throw an exception if that happens; it really depends on the quality of the source data.)</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