所以我很难理解如何在 C# 中使用 linq。我找到了一些示例,但找不到与我正在寻找的案例相匹配的示例。给定以下xml:
<?xml version="1.0"?>
<dwml version="1.0" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http
://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://gra
phical.weather.gov/xml/DWMLgen/schema/DWML.xsd">
<head>
<product srsName="WGS 1984" concise-name="time-series" operational-mode="off
icial">
<title>NOAA's National Weather Service Forecast Data</title>
<field>meteorological</field>
<category>forecast</category>
<creation-date refresh-frequency="PT1H">2013-09-18T07:17:35Z</creation-dat
e>
</product>
<source>
<more-information>http://graphical.weather.gov/xml/</more-information>
<production-center>Meteorological Development Laboratory<sub-center>Produc
t Generation Branch</sub-center></production-center>
<disclaimer>http://www.nws.noaa.gov/disclaimer.html</disclaimer>
<credit>http://www.weather.gov/</credit>
<credit-logo>http://www.weather.gov/images/xml_logo.gif</credit-logo>
<feedback>http://www.weather.gov/feedback.php</feedback>
</source>
</head>
</dwml>
我想打印出创建日期属性值。我能够做到这一点的唯一方法是通过下面的代码:
XElement xElement = XElement.Load(XmlReader.Create(new StringReader(xml)));
var nodes = xElement.Elements("head").Elements("product").Elements("creation-date");
foreach (var attr in nodes)
{
Console.WriteLine("value = " + attr.Value);
}
我确信使用查询有更好的方法。我尝试使用 select 语句,但无需进行一些操作就无法使其正常工作。只需要一个查询而不必遍历结果集会非常好。