1

I'm using VS2010 C#. I have an XML file being read in via XDocument. I need to load the XML data into a class or a var and then be able to access that data to print out to textboxes in a windows form.

I have tried a few things. XDocument.Parse is getting the XML, because I can print it out to a text box and it is all there & correct. From there, however, the data does not seem to be reading into the class or var. (count of 0, elements are null, etc).

I was following this tutorial, but it is quite old now: http://tech.pro/tutorial/743/introduction-to-linq-simple-xml-parsing

Can anyone point me to how 1) I can load the data into a list and 2) access the sub-elements to print out to a text box?

The code:

XDocument xmlResponse = XDocument.Parse( e.Result );

var hds =
 (from hdi in xmlResponse.Descendants("HDInfo")
  select new HDInfo
  {
   freeSpace = (long)hdi.Element("freeSpace"),
   percentFree = (float)hdi.Element("percentFree"),
   volume = (String)hdi.Element("volume"),
  });

The XML:

<ArrayOfHDInfo xmlns="http://schemas.datacontract.org/2004/07/project" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
 <HDInfo>
  <freeSpace>187783532544</freeSpace>
  <percentFree>75.1457443</percentFree>
  <volume>C:\</volume>
 </HDInfo>
 <HDInfo>
  <freeSpace>583875145728</freeSpace>
  <percentFree>77.83411</percentFree>
  <volume>D:\</volume>
 </HDInfo>
</ArrayOfHDInfo>

1 Answer 1

2

You have to use XNamespace object within your query:

var ns = XNamespace.Get("http://schemas.datacontract.org/2004/07/project");

var hds =
 (from hdi in xmlResponse.Descendants(ns + "HDInfo")
  select new HDInfo
  {
   freeSpace = (long)hdi.Element(ns + "freeSpace"),
   percentFree = (float)hdi.Element(ns + "percentFree"),
   volume = (String)hdi.Element(ns + "volume"),
  });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.