再会。首先,让我警告您:我的 XML 知识是基础知识,所以我可能在我的研究中找到了正确的答案,只是不明白如何应用它。
我目前有一些 C# 代码读取国家气象服务 XML 文件并在元素中查找文本以确定是否有天气警报。这行得通,但我更愿意测试另一个元素的存在,然后使用它的文本将警报写入网页。带有警告的 XML 文件示例如下:http: //www.co.frederick.va.us/dev/scrapewarning.xml。我想测试是否存在,<cap:event>
然后使用它的文本来填充网页上的文字。
这就是我现在正在做的事情:
// Create an instance of XmlReader with the warning feed and then load it into a SyndicationFeed.
XmlReader reader = XmlReader.Create(strWarningFeed);
SyndicationFeed feed = SyndicationFeed.Load(reader);
// Read through the XML, pull out the items we need depending on whether or not there is a warning.
foreach (var str in feed.Items)
{
if (str.Title.Text.Contains("no active"))
{
weatherWarning.Visible = false;
}
else
{
string strTitle = str.Title.Text;
string strId = str.Id.ToString();
strTitle = strTitle.Substring(0, strTitle.LastIndexOf("issued"));
litOut.Text += String.Format("<p class=\"warningText\">{0}</p><p class=\"warningText\"><a href=\"{1}\">Read more.</a></p>", strTitle, strId);
}
}
因此,与其看到它的标题包含“无活动”,我宁愿询问文档是否有一个名为的元素<cap:event>
,然后使用它的文本。伪代码:
foreach (var str in feed.Items)
{
if (<cap:event> doesn't exist)
{
weatherWarning.Visible = false;
}
else
{
string strTitle = <cap:event>.Text;
}
}
如果您需要更多信息,请告诉我。提前感谢您的帮助。