Adam_G
Adam_G

Reputation: 7879

Use Separate Elements From XML File

In the below XML file, the elements that needs to be utilized together are broken up between XElements. (This is beyond my control). For example, I would like to use ToolVersion in conjunction with Result.

<DiagReport>
<LicensingData>
  <ToolVersion>6.3.9431.0</ToolVersion>
  <LicensingStatus>SL_LICENSING</LicensingStatus>
</LicensingData>
<Health>
  <Result>PASS</Result>
  <TamperedItems></TamperedItems>
</Health>
<Genuine>
  <ServerProps>GenuineId</ServerProps>
</Genuine>
</DiagReport>

I know how to get the deepest children from this post, but this iterates one by one. In the example above, I might need ToolVersion and Result, but then need to go back to LicensingStatus, and pick up where I left off. (The code doesn't need to explicitly ignore Result, since I can just ignore that in my switch statements.

Is this possible?

Upvotes: 1

Views: 155

Answers (2)

Michael Bray
Michael Bray

Reputation: 15285

Parse it into an XmlDocument, then pull the values you require with XPath:

XmlDocument xml = new XmlDocument();
xml.LoadXml(yourXmlString);
string toolVersion = xml.SelectSingleNode("/DiagReport/LicensingData/ToolVersion").InnerText;
string result = xml.SelectSingleNode("/DiagReport/Health/Result").InnerText

You can learn more about XPath at W3Schools XPath Tutorial.

Or you can use XDocument:

XDocument xml = XDocument.Parse(yourXmlString);
string toolVersion = xml.Element("DiagReport").Element("LicensingData").Element("ToolVersion").Value;
string result = xml.Element("DiagReport").Element("Health").Element("Result").Value;

Note that this assumes that all of the referenced elements exist.

Upvotes: 5

sa_ddam213
sa_ddam213

Reputation: 43636

You can just loop though all the DiagReport elemets and select the values from LicensingData and Health that you need.

In this example they are just stored in a anonymous object, but you can create your own typed object is required.

  var xmlDocument = XDocument.Load(@"C:\test.xml");
  var results = xmlDocument.Elements("DiagReport").Select(x => new 
  {
      ToolVersion = x.Descendants("ToolVersion").FirstOrDefault().Value,
      LicensingStatus = x.Descendants("LicensingStatus").FirstOrDefault().Value,
      Result = x.Descendants("Result").FirstOrDefault().Value
  });

  // print results
  foreach (var item in results)
  {
      Console.WriteLine("ToolVersion: {0}, LicensingData: {1}, Result: {2}", item.ToolVersion, item.LicensingStatus, item.Result);
  }

Upvotes: 2

Related Questions