0

再会。首先,让我警告您:我的 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;
    }
}

如果您需要更多信息,请告诉我。提前感谢您的帮助。

4

2 回答 2

0

使用linq to xml,检查是否存在(以及任何现有值)之类的事情要容易得多。如果将 xml 加载到 XDocument 中,则可以使用 linq 的优点来查询元素和后代。无需在 IDE 前或能够非常仔细地查看该示例 xml,例如 doc.Descendants("weather").Where(e => e.Element("event") == "whatever") .

于 2012-07-30T13:42:25.363 回答
0

我相信您缺少名称空间管理器。以下是代码如何与 XmlDocument 一起使用:

        var xmlDoc = new XmlDocument();
        xmlDoc.Load(@"http://www.co.frederick.va.us/dev/scrapewarning.xml");
        var nsm = new XmlNamespaceManager(xmlDoc.NameTable);
        nsm.AddNamespace("s", "http://www.w3.org/2005/Atom");
        nsm.AddNamespace("cap", "urn:oasis:names:tc:emergency:cap:1.1");
        var nodes = xmlDoc.SelectNodes("//s:entry[cap:event]", nsm);
于 2012-07-30T14:51:07.207 回答