繁体   English   中英

如何在SyndicationFeed中使用非标准名称空间?

[英]How can I use non-standard namespaces with SyndicationFeed?

美好的一天。 首先,让我警告您:我对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);
    }
}

因此,与其查看标题是否包含“ no active”,不如询问文档是否包含名为<cap:event>的元素,然后使用其文本。 伪码:

foreach (var str in feed.Items)
{
    if (<cap:event> doesn't exist)
    {
        weatherWarning.Visible = false;
    }
    else
    {
        string strTitle = <cap:event>.Text;
    }
}

让我知道您是否需要更多信息。 在此先感谢您的帮助。

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

我相信您缺少名称空间管理器。 这是代码与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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM