如何使用LINQ C#正确搜索xml文档

时间:2015-09-29 20:42:07

标签: c# xml linq

嘿伙计们和gals我很难搞清楚如何正确搜索xml文档。我一直在阅读其他形式如今疯狂,但似乎无法理解它。希望有人可以给我一些更详细的信息,告诉我如何正确使用LINQ。这是XML文件。

<?xml version="1.0" encoding="utf-8"?>
<body>
  <Customers>
    <Client>
      <Firstname Value="someguy" />
      <LastName Value="test" />
      <PhoneNumber Value="541555555" />
      <Address Value="55 nowhere" />
      <City Value="sometown" />
      <State Value="somestate" />
    </Client>
  </Customers>
</body>

我要完成的工作是返回与客户名称匹配的每个元素的所有值。这是我的代码。

       IEnumerable<XElement> test = doc.Root.Descendants()
            .Where(nodeName => nodeName.Name == "Client"
            && nodeName.Descendants().Any(x => x.Name == "Firstname"
            && x.Value == "someguy"));

        foreach (XElement m in test)
        {
            MessageBox.Show(m.ToString());
        }

真的很感激帮助。如果可能的话,还请解释一下,如果你愿意,使用LINQ的想法就像格式一样。不确定如何解释我在问什么,但大部分只是更了解它的工作方式或格式等...

修改

我已经尝试过给出的解决方案,但似乎没有任何东西可行。请告诉我这里我做错了什么。

        private void button2_Click(object sender, EventArgs e)
    {
        string seach = txtSearch.Text;

        XDocument doc = XDocument.Load(@"C:\users\tim\desktop\test.xml");

        var result = doc.Elements("Customers")
            .Elements("Client")
            .Where(x => x.Elements("Firstname")
                         .Where(c => c.Attribute("Value").Value == "someguy")
                         .Any())
            .ToList();

        foreach (var m in result)
        {
            MessageBox.Show(m.ToString());
        }
    }

修改

好的,所以我现在已经让它工作并输出我正在寻找的数据。有人可以告诉我是否有更有效的方式来做我在此编辑下面发布的内容。

        private void button2_Click(object sender, EventArgs e)
    {
        string seach = txtSearch.Text;

        XDocument doc = XDocument.Load(@"C:\users\tim\desktop\test.xml");

        var result = (from clientNode in doc.Root.Descendants("Client")
                      from name in clientNode.Descendants("Firstname")
                      where name.Attribute("Value").Value == "someguy"
                      select new
                      {
                          Fname = clientNode.Element("Firstname").Attribute("Value").Value,
                          Lname = clientNode.Element("LastName").Attribute("Value").Value,
                          Phone = clientNode.Element("PhoneNumber").Attribute("Value").Value,
                          Address = clientNode.Element("Address").Attribute("Value").Value,
                          City = clientNode.Element("City").Attribute("Value").Value,
                          State = clientNode.Element("State").Attribute("Value").Value
                      });

        foreach (var m in result)
        {
            MessageBox.Show(m.Fname + "\n" +
                            m.Lname + "\n" +
                            m.Phone + "\n" +
                            m.Address + "\n" +
                            m.City + "\n" +
                            m.State);
        }

2 个答案:

答案 0 :(得分:8)

您可以使用XElement并使用以下LINQ查询进行搜索:

XElement doc = XElement.Parse(xml);
var result = doc.Elements("Customers")
                .Elements("Client")
                .Where(x => x.Elements("Firstname")
                             .Where(c => c.Attribute("Value").Value == "someguy")
                             .Any())
                .ToList();

所以输入:

var xml =
@"<?xml version=""1.0"" encoding=""utf-8""?>
<body>
    <Customers>
    <Client>
        <Firstname Value=""someguy"" />
        <LastName Value=""some last name"" />
        <PhoneNumber Value=""123456"" />
        <Address Value=""some where"" />
        <City Value=""some town"" />
        <State Value=""some state"" />
    </Client>
    <Client>
        <Firstname Value=""someotherguy"" />
        <LastName Value=""some other last name"" />
        <PhoneNumber Value=""123456"" />
        <Address Value=""some other where"" />
        <City Value=""some other town"" />
        <State Value=""some other state"" />
    </Client>
    </Customers>
</body>";

XElement doc = XElement.Parse(xml);
var result = doc.Elements("Customers")
                .Elements("Client")
                .Where(x => x.Elements("Firstname")
                             .Where(c => c.Attribute("Value").Value == "someguy")
                             .Any())
                .ToList();

结果将是:

<Client>
    <Firstname Value=""someguy"" />
    <LastName Value=""some last name"" />
    <PhoneNumber Value=""123456"" />
    <Address Value=""some where"" />
    <City Value=""some town"" />
    <State Value=""some state"" />
</Client>

您可以显示值,例如:

MessageBox.Show(string.Format("Firstname: {0}\nLastName: {1}\nPhoneNumber: {2}\nAddress: {3}\nCity: {4}\nState: {5}",
                result[0].Element("Firstname").Attribute("Value").Value,
                result[0].Element("LastName").Attribute("Value").Value,
                result[0].Element("PhoneNumber").Attribute("Value").Value,
                result[0].Element("Address").Attribute("Value").Value,
                result[0].Element("City").Attribute("Value").Value,
                result[0].Element("State").Attribute("Value").Value));

注意:

  • 如果您知道结果应包含0或1个元素,则可以使用FirstOrDefault()代替ToList();
  • 元素名称区分大小写,因此请注意名字,例如。
  • 您可以使用XElement.Load()从文件加载,例如XElement doc = XElement.Load(@"d:\file.xml");
  • 如果以这种方式.Where(c => c.Name.ToString().ToLower() == "Customers".ToLower())
  • 选择元素,查询将更具容错能力
  • 如果以这种方式.Where(c => c.Attributes("Value").Where(a=>a.Value == "someguy").Any())
  • 选择属性,查询将更具容错能力

答案 1 :(得分:4)

作为@Reza Aghaei解决方案的替代方案,XPath也是一种解决方案

var xml =
@"<?xml version=""1.0"" encoding=""utf-8""?>
<body>
    <Customers>
    <Client>
        <Firstname Value=""someguy"" />
        <LastName Value=""some last name"" />
        <PhoneNumber Value=""123456"" />
        <Address Value=""some where"" />
        <City Value=""some town"" />
        <State Value=""some state"" />
    </Client>
    <Client>
        <Firstname Value=""someotherguy"" />
        <LastName Value=""some other last name"" />
        <PhoneNumber Value=""123456"" />
        <Address Value=""some other where"" />
        <City Value=""some other town"" />
        <State Value=""some other state"" />
    </Client>
    <Client>
        <Firstname Value=""someguy"" />
        <LastName Value=""some other last name"" />
        <PhoneNumber Value=""12345634543"" />
        <Address Value=""some other where"" />
        <City Value=""some other town"" />
        <State Value=""some other state"" />
    </Client>
    </Customers>
</body>";
XElement doc = XElement.Parse(xml);

foreach(var client in doc
 .XPathSelectElements("./Customers/Client/Firstname[@Value='someguy']")
 .Select(x => x.Parent))
    Console.WriteLine (client);

如果您更喜欢 Linq To Xml 解决方案:

var results = (from c in doc.Descendants("Client")
            from f in c.Descendants("Firstname")
             where (string)f.Attribute("Value") == "someguy"
             select c).ToList();
foreach(var r in results)
    Console.WriteLine (r);

How to: Write Linq to Xml Queries with Complex Filtering