[英]Reading non-standard elements in a SyndicationItem with 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.