簡體   English   中英

Linq查詢以在文本框中顯示XML中的字符串

[英]Linq Query to display string from XML in a TextBox

我正在嘗試進行一個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>

在第一個代碼段中,tagBox指的是另一個TextBox,其中包含一個字符串,該字符串最初是從我的string元素的id屬性中提取的。 這個想法是掃描XML以查找匹配的ID,然后將comment元素的值簡單地放在textBox

只是改變

textBox.Text = comm;

textBox.Text = comm.FirstOrDefault();

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 = "";
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM