如何使用LINQ填充包含带有空格属性的NWS XML数据的数据网格
本文关键字:数据 网格 NWS XML 属性 数据网 空格 LINQ 何使用 填充 包含带 | 更新日期: 2023-09-27 18:10:31
我正在尝试用National Weather services REST服务提供的XML数据填充DataGrid。我能够获得数据,但在我的WPF应用程序中填充DataGrid控件时一直存在问题。
问题似乎是NWS返回的元素中的空格。我不知道该怎么做。任何帮助都将是非常感激的。
using System.Linq;
using System.Windows;
using System.Net;
using System.Xml.Linq;
namespace datagrid
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
string requestUrl = "http://www.weather.gov/forecasts/xml/sample_products/browser_interface/ndfdXMLclient.php?lat=47.5055&lon=-111.2831&product=time-series&maxt=maxt&mint=mint&wspd=wspd&wdir=wdir&wgust=wgust";
WebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest;
WebResponse response = request.GetResponse() as HttpWebResponse;
var xmlDoc = XDocument.Load(response.GetResponseStream(),LoadOptions.PreserveWhitespace);
var i = from item in xmlDoc.Descendants("wind-speed")
select new
{
WindSpeed = item.Attribute("Wind Speed").Value
};
dataGrid1.ItemsSource = i.ToList();
}
}
}
当我运行代码时,我得到这个异常
System.Xml.XmlException was unhandled by user code
HResult=-2146232000
Message=The ' ' character, hexadecimal value 0x20, cannot be included in a name.
Source=System.Xml
LineNumber=0
LinePosition=5
StackTrace:
at System.Xml.XmlConvert.VerifyNCName(String name, ExceptionType exceptionType)
at System.Xml.Linq.XName..ctor(XNamespace ns, String localName)
at System.Xml.Linq.XNamespace.GetName(String localName)
at System.Xml.Linq.XName.Get(String expandedName)
at System.Xml.Linq.XName.op_Implicit(String expandedName)
at datagrid.MainWindow.<.ctor>b__0(XElement item) in 'datagrid'MainWindow.xaml.cs:line 24
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at datagrid.MainWindow..ctor() in datagrid'MainWindow.xaml.cs:line 28
InnerException:
查看您的代码,我猜您正在尝试检索XML文件的这一部分(值项):
<wind-speed type="sustained" units="knots" time-layout="k-p3h-n34-3">
<name>Wind Speed</name>
<value>20</value>
<value>13</value>
...
<value>3</value>
</wind-speed>
试着用这个查询代替:
var i = from item in xmlDoc.Descendants("wind-speed") '' get wind-speed descendants
where item.Elements("name").First().Value == "Wind Speed" '' since there are two types of wind-speed nodes,
'' we want that whose first item is called "Wind Speed"
from value in item.Elements("value") '' get values inside wind-speed node
select new
{
WindSpeed = value.Value '' return values inside wind-speed node
};
我认为当你提到带有空格的属性时,你说的是<name>Wind Direction</name>
,但这不是一个属性。以这一行为例:
<wind-speed type="sustained" units="knots" time-layout="k-p3h-n34-3">
type
, units
和time-layout
是属性,正如您所看到的,它们的名称中没有空格,因为这是不允许的。