大家好!我无法找到一个教程解释的正确方法的代码这一点。我认为这将是从标题和我想要做的代码清晰。这两个错误,我收到的是我的if语句是放错了地方,且变量“箭”被分配但从未使用过。我知道这归结为简单的语法,所以我感谢大家的时间。

void DATABASEinfo_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
    {
        if (e.Error != null)
            return;

        XElement xmlitem = XElement.Parse(e.Result);

        var list = new List<DATABASEinfoViewModel>();            


        foreach (XElement item in xmlitem.Element("channel").Elements("item"))
        {
            var title = item.Element("title");
            var titlevalue = (title == null) ? null : title.Value;
            var description = item.Element("description");
            var descriptionvalue = (description == null) ? null : description.Value;                
            var arrow = (xmlitem.Element("title").Value.Contains("DATABASE Up"))
                ? "up" : null;


            list.Add(new DATABASEinfoViewModel
            {
                Title = titlevalue,
                Description = descriptionvalue,
                Arrow = arrow,                   
            });
        }                       

        DATABASEinfoList.ItemsSource = list;           
    }          

    public class DATABASEinfoViewModel
    {
        public string Title { get; set; }
        public string Description { get; set; }
        public string Arrow { get; set; } 

奇怪的是,如果我的变化:

var arrow = (xmlitem.Element("title").Value.Contains("DATABASE Up"))

要:

var arrow = (xmlitem.Element("channel").Value.Contains("DATABASE Up"))

它显示“上”为所有条目。下面是XML文件的一个例子:

<rss version="2.0">
<channel>
<title> DATABASE Status</title>
<description>DATABASE status updates</description>      

<item>
<title>First status is DATABASE Up</title>
<description>First Content</description>
</item>

<item>
<title>Second status is DATABASE Up</title>
<description>Second Content</description>
</item>

</channel>
有帮助吗?

解决方案

var arrow = (xmlitem.Element("title").Value.Contains("DATABASE Up")) 

实际上应

var arrow = (item.Element("title").Value.Contains("DATABASE Up")) 

您应该查询的项目,不是 xmlitem

正如在其他的答案提到的,你也应该检查元件访问其值之前存在。

其他提示

如果没有返回结果,你可以分配给VAR箭头。

如果你试图做这样的事?

    string arrow = "";
    if (xmlitem.Element("description").Value.Contains("DATABASE Up"))
    {
        arrow = ("up");                
    }   

这不是完全清楚我你想要做什么。如果description包含“数据库恢复”你要arrow的值确定为“上”,否则什么?空?

string arrow = null;

if (xmlitem.Element("description").Value.Contains("DATABASE Up")) 
{ 
    arrow = ("up");                 
}                 

var arrow = (xmlitem.Element("description").Value.Contains("DATABASE Up"))
            ? "up" : null;

修改

和你为什么要设置DATABASEinfoList.ItemsSource = list两个foreach循环内,外面再?在一个内部或许应该走了。

此外,还有一个内在的问题,通过您的评论在米克的答案所示。这些电话:

 item.Element("[elementName]").Value

假定该元件存在。如果没有,你会打电话给一个空的Value属性getter,抛出一个NullReferenceException。如果有一个机会,该元素将是零,那么你需要调用值前检查是:

 var element = item.Element("[elementName]");
 var value = (element == null) ? null : element.Value;
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top