我正在尝试使用消息框来显示元素,但是当我运行应用程序时,消息框不会弹出
string xml = @"<?xml version='1.0' encoding='UTF-8'?>
<widgets>
<widget>
<url>~/Portal/Widgets/ServicesList.ascx</url>
<castAs>ServicesWidget</castAs>
<urlType>ascx</urlType>
<parameters>
<PortalCategoryId>3</PortalCategoryId>
</parameters>
</widget>
<widget>
<url>www.omegacoder.com</url>
<castAs>ServicesWidget</castAs>
<urlType>htm</urlType>
<parameters>
<PortalCategoryId>41</PortalCategoryId>
</parameters>
</widget>
</widgets>";
XDocument loaded = XDocument.Parse( xml );
var widgets = from x in loaded.Descendants( "widget" )
select new
{
URL = x.Descendants( "url" ).First().Value,
Category = x.Descendants( "PortalCategoryId" ).First().Value
};
MessageBox.Show("one");
foreach ( var wd in widgets ){
MessageBox.Show("two");
}
MessageBox.Show( “1”);出现。 的MessageBox.show( “二”);永远不会弹出
如果我想看到小部件的数量&gt;我是C#的新手 感谢
答案 0 :(得分:2)
如果您尝试MessageBox.Show(widgets.Count().ToString())
,我会下注0
。定义for循环的行为,对具有0个元素的集合执行NO迭代。所以“两个”永远不会显示出来。
至于为什么它会为零,如果是的话显然是个问题!也许你需要循环通过from x in loaded.Descendants( "widgets/widget" )
???
我不记得XDocument是否强迫您吞下文档元素或不像XMLDocument那样。
答案 1 :(得分:2)
替换
MessageBox.Show("one");
通过
MessageBox.Show(widgets.Count()); //.Count(), not .Count
检查是否有任何要循环的元素!
答案 2 :(得分:2)
您可以使用以下命令替换LINQ查询:
var widgets = from x in loaded.Descendants("widgets").Descendants( "widget" )
select new
{
URL = x.Descendants( "url" ).First().Value,
Category = x.Descendants( "PortalCategoryId" ).First().Value
};
<强>更新强> 两个版本的LINQ都应该正常工作。我的错误 Descendants 不仅可以指向直接嵌套的节点,还可以指向子树中的所有节点。
可能的问题原因: 但是,请注意,为了显示第二个消息框,您必须关闭第一个消息框。我刚刚对此进行了测试,但它确实有效。
建议的解决方案: 为了能够显示带有消息的多个对话框,您可以在项目中创建自己的表单类,实例化它并使用 Show()方法显示它,即: 您可以添加新的 Windows窗体,将其命名为 MessageForm 并使用以下代码:
//MessageBox.Show(new Form(), "one");
MessageForm msgDlg = new MessageForm() { Message = "one" };
msgDlg.Show(this);
foreach (var wd in widgets)
{
//MessageBox.Show(new Form(), "two");
MessageForm msgDlgS = new MessageForm() { Message = "two" };
msgDlgS.Show(this);
}
它应该按预期工作。