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>
4

1 回答 1

2

您必须XNamespace在查询中使用对象:

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"),
  });
于 2013-07-08T21:52:20.823 回答