[英]C# XML Linq Parsing
我正在使用VS2010 C#。 我有一个通过XDocument读取的XML文件。 我需要将XML数据加载到类或var中,然后能够访问该数据以在Windows窗体中打印到文本框。
我已经尝试了几件事。 XDocument.Parse正在获取XML,因为我可以将其打印到文本框中,并且所有内容都正确无误。 但是,从那里看来,数据似乎并没有读入类或var中。 (计数为0,元素为空,等等)。
我一直在关注本教程,但是现在它已经很老了: http : //tech.pro/tutorial/743/introduction-to-linq-simple-xml-parsing
谁能指出我如何1)我可以将数据加载到列表中,以及2)访问子元素以打印到文本框?
编码:
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"),
});
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>
您必须在查询中使用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"),
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.