【问题标题】:Linq Query to display string from XML in a TextBoxLinq Query 在文本框中显示来自 XML 的字符串
【发布时间】:2011-08-03 19:19:58
【问题描述】:

我正在尝试进行 Linq 查询,该查询将从 XML 文件中检索字符串值并将其放入 TextBox。我想我需要使用FirstorDefault(),但我不知道如何正确使用它。这是我目前拥有的:

var comm = from comment in xdoc.Descendants("string")                   
           where comment.Attribute("id").Value == tagBox.Text
           select comment.Element("comment").Value;

textBox.Text = comm; //Essentially

基本上,我的 XML 文件如下所示:

<root>
    <string id = "STRING_ID1">
        <element1 />
        <comment> Some string </comment>
        ...
    </string>
</root>

在第一个代码 sn-p 中,tagBox 引用另一个 TextBox,其中包含一个字符串,该字符串最初是从我的 string 元素的 id 属性中提取的。想法是扫描 XML 以查找匹配的 ID,然后简单地将 comment 元素的值放在 textBox 中。

【问题讨论】:

    标签: c# .net xml linq textbox


    【解决方案1】:

    只是改变

    textBox.Text = comm;
    

    textBox.Text = comm.FirstOrDefault();
    

    【讨论】:

    • comm 是 XElement,而不是 IEnumerable,因为他使用的是 Element("comment")。
    • 其实 comm 是一个 IEnumerable,这是我的问题。
    • @Dave:实际上是IEnumerable&lt;string&gt;...它被投影到XElementValue
    • @DaveShaw:不,commIEnumerable&lt;string&gt;comment.Element("comment").Value 仅在 linq 查询的 select 部分中!
    【解决方案2】:

    FirstOrDefault 的用法如下

    var str = (from str in xdoc.Descendants("string")                   
               where str.Attribute("id").Value == tagBox.Text
               select str).FirstOrDefault();
    
    if(str != null)
    {
        textBox.Text = str.Element("comment").Value;
    }
    else
    {
        textBox.Text = "";
    }
    

    【讨论】:

    • .Value == tagBox.Text 在 LINQ 表达式中有效吗?我会认为 .Contains(tagBox.Text) 是将运行时值放入查询的方式。
    • @DaveShaw,你说得对,我忘了删除它。代码的整个语义还是不正确,所以我全部更改了。
    • @Tim:它们都是可能的,但它们在语义上是不同的。 "==" 是完全匹配,而 ".Contains()" 更像是通配符匹配。如果您想指定文化并进行完全匹配,我会使用“.Equals()”
    • @Mr Happy - 感谢您提供的信息。我没有意识到这些差异。好东西要知道。
    猜你喜欢
    • 2015-05-15
    • 1970-01-01
    • 1970-01-01
    • 2011-09-23
    • 1970-01-01
    • 1970-01-01
    • 2015-10-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多