2

我写了这个:

        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);

由于我想加载这些数据,所以我想将它们放入变量中,以便稍后将它们放入 textBoxes、radioBoxes 等。现在我只知道如何使用 MessageBox 显示它。

4

3 回答 3

4

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

创建一个新的公共类:

    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);
    }
于 2013-07-21T17:59:20.797 回答
1

您可以调用Enumerable.ToList将它们存储在集合中以备后用。

var result = query.ToList();
foreach (string data in result)
        MessageBox.Show(data);

//result is available for later use
于 2013-07-21T17:47:44.967 回答
1

好的,我不知道是否有更好的方法来实现我想要的,但它确实有效。

    public class Data
    {
    public string name { get; set; }
    public string breed { get; set; }
    public string sex { get; set; }
    }

和方法:

                  XDocument doc = XDocument.Load(@"test.xml");
                  string nodeName = "Mike";
                  var data = from q in doc.Descendants("dogs")
                  where (string)q.Attribute("name") == nodeName
                      select new Data
                      {
                          name = q.Attribute("name").Value,
                          breed = q.Element("breed").Value,
                          sex = q.Element("sex").Value
                      };
                  foreach (var element in data)
                  {
                      textBox1.Text = element.name;
                      comboBox1.Text = element.sex;
                      textBox2.Text = element.breed;
                  }
于 2013-07-23T11:44:51.830 回答