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

c# Find element/s with a specific child element

Sample

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

现在看看我的代码和 XMLfile,您会发现它们与上面的相同 link。问题是我的代码只打印与文本框值匹配的第一组。

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() -_-

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

试试这个代码:

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 元素中是否有任何元素等于指定的文本。

在两个组中你有相同的 ip

<ip> 10.3.4 </ ip>

在这种情况下,它甚至会将两个组放在一起。

我建议通过检查 'name' 再做一个条件。

var xml = XDocument.Parse(xmlString);
// a, b
string[] matchingNames = xml.Root.Elements("group")
    .Where(g => g.Elements("ip").Any(e => e.Value == textBoxText))
    .Select(g => g.Attribute("name").Value).ToArray();

Select 来自任何子 ip 元素包含文本框文本的组的属性名称。