c#查找具有特定子元素的元素

时间:2018-03-23 12:00:49

标签: c# linq-to-xml

Sample

示例代码查找其子元素'值与texbox中输入的值匹配的元素的属性名称

现在查看我的代码和XML文件,您会发现它们与上述链接完全相同。问题是我的代码只打印与文本框值匹配的第一个组。

XML
<?xml version="1.0" encoding="utf-8"?>
<groups>
  <group name="a">
    <ip>10.3.4</ip>
    <ip>10.1.4</ip>
  </group>
  <group name="b">
    <ip>10.2.1</ip>
    <ip>10.3.4</ip>
    <ip>10.55.55</ip>
  </group>
 </groups>

代码

XElement root = XElement.Load("c:\etc);
IEnumerable<XElement> tests =
   from el in root.Elements("group")
   where (string)el.Element("ip") == textBox1.Text
   select el;

foreach (XElement el in tests)
   Console.WriteLine((string)el.Attribute("name"));

问题出在where子句中。因为如果我对它进行评论,系统将打印两个组名,但是当where子句处于活动状态时,它总是只返回1个组。也可以使用FirstOrDefault() - _-

4 个答案:

答案 0 :(得分:0)

var tests =
    from el in root.Elements("group")
    where el.Elements("ip").Any(o => o.Value == textBox1.Text)
    select el;

答案 1 :(得分:0)

试试这段代码:

XElement root = XElement.Load(@"your path to a file");
//set text box to some default value to test if function will work
textBox1.Text = "10.1.4";
//here I used etension method, commented is alternative version, for better understanding
IEnumerable<XElement> tests = root.Elements("group").Where(gr => gr.Elements("ip").Any(ip => ip.Value == textBox1.Text));
//IEnumerable<XElement> tests = root.Elements("group").Where(gr => gr.Elements("ip").Where(ip => ip.Value == textBox1.Text).Count() > 0);
foreach (XElement el in tests)
    //Console.WriteLine((string)el.Attribute("name"));
    MessageBox.Show((string)el.Attribute("name"));

您将代码单个元素与文本框的文本进行比较时,您的代码无法正常工作。你想要的是检查ip元素中是否有任何元素等于指定的文本。

答案 2 :(得分:0)

在两组中你都有相同的ip

<ip> 10.3.4 </ ip>

在这种情况下,它甚至可以将两个小组聚集在一起。

我建议通过检查'姓名'来再做一个条件。

答案 3 :(得分:0)

db.collection_name.find().pretty()

从任何子ip元素包含文本框文本的组中选择属性名称。

相关问题