0

良い一日。最初に警告しておきますが、XML に関する私の知識は基本的なものなので、研究で正しい答えを見つけたとしても、それを適用する方法を理解していないだけかもしれません。

私は現在、National Weather Service XML ファイルを読み取り、要素内のテキストを検索して気象警報があるかどうかを判断する C# コードをいくつか持っています。それは機能しますが、別の要素の存在をテストしてから、そのテキストを使用してアラートを Web ページに書き出すほうがよいでしょう。警告のある XML ファイルの例は、http: //www.co.frederick.va.us/dev/scrapewarning.xmlです。<cap:event>の存在をテストし、そのテキストを使用して Web ページのリテラルを埋めたいと考えています。

これが私が今していることです:

// 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;
    }
}

さらに情報が必要な場合はお知らせください。助けてくれてありがとう。

4

2 に答える 2

0

の存在 (および既存の値) のチェックなどは、linq to xml を使用するとはるかに簡単になります。xml を XDocument にロードすると、linq の利点を利用して要素と子孫を照会できます。IDE の前にいなかったり、doc.Descendants("weather").Where(e => e.Element("event") == "whatever") のようなサンプル xml を詳しく調べたりすることができません。 .

于 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 に答える