gpt4 book ai didi

c# - Linq 到 XML : from query to variable

转载 作者:行者123 更新时间:2023-12-03 00:21:27 25 4
gpt4 key购买 nike

我写的是:

        XDocument doc = XDocument.Load("test.xml");
string nodeName = "Mike";
var query = from el in doc.Descendants("dogs")
where (string)el.Attribute("name") == nodeName
select
"Name: " + nodeName
+ "\n" + "Breed: " + (string)el.Element("breed")
+ "\n" + "Sex: " + (string)el.Element("sex");
foreach (string data in query)
MessageBox.Show(data);

因为我想加载这些数据,所以我想将它们放入变量中,以便稍后能够将它们放入文本框、单选框等中。目前我只知道如何用 MessageBox 显示它。

最佳答案

不确定您是否指的是这个,但您可以尝试一下:

创建一个新的公共(public)类:

    public class XmlResut
{
public string Name { get; set; }
public string Breed { get; set; }
public string Sex { get; set; } // Maybe a enum would fit this property better
}

现在,您可以更改 LINQ 以使用 select new ( http://www.dotnetperls.com/select-new ) 创建已定义类的新实例

    XDocument doc = XDocument.Load("test.xml");
string nodeName = "Mike";
var query = from el in doc.Descendants("dogs")
where (string)el.Attribute("name") == nodeName
select new XmlResult(){
Name = nodeName,
Breed = (string)el.Element("breed")
Sex = (string)el.Element("sex")
};
foreach (string data in query)
{
Console.WriteLine(data.Name);
Console.WriteLine(data.Breed);
Console.WriteLine(data.Sex);
}

关于c# - Linq 到 XML : from query to variable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17775094/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com