【问题标题】:How to check all child tags of a particular parent tags count?如何检查特定父标签计数的所有子标签?
【发布时间】:2018-11-01 10:04:46
【问题描述】:

这是一个示例 xml

<?xml version="1.0" encoding="utf-8"?>
<random>
  <chkr id="1">
    <ab>10.100.101.18</ab>
    <xy>5060</xy>
    <tt>pop</tt>
    <qq>pop</qq>
  </chkr>
  <chkr id="2">
    <ab>tarek</ab>
    <tt>tarek</tt>
    <ab>ffff</ab>
    <foo>pop</foo>
  </chkr>
  <chkr id="3">
    <ab>adf</ab>
    <foo>adf</foo>
    <tt>fadsf</tt>
    <ab>fadsf</ab>
    <tt>036</tt>
    <foo>.3</foo>
    <ssd>wolk</ssd>
  </chkr>
</random>

我想在每个父标签&lt;chkr&gt; 中搜索标签&lt;ab&gt;&lt;tt&gt; 以外的标签,并多次获取出现在该父节点中的标签的名称。即在上面的示例 xml 中,输出应该是 &lt;chkr id="3"&gt; 包含标签 &lt;foo&gt; 多次。

如何使用 LINQ-TO-XML 做到这一点?

【问题讨论】:

    标签: c# xml-parsing linq-to-xml


    【解决方案1】:

    按所有后代的名字分组是一个非常简单的解决方案: (x 是您的 XDocument 的名称)

    foreach (var e in x.Descendants("chkr"))
    {
        foreach (var v in e.Descendants()
                           .Where(ee => ee.Name != "ab" && ee.Name != "tt")
                           .GroupBy(ee => ee.Name)
                           .Select(ee => new { Name = ee.Key, Count = ee.Count() }))
        {
            if (v.Count > 1)
                Console.WriteLine($"<chkr id={e.Attribute("id").Value}> contains the tag <{v.Name}> {v.Count} times.");
        }
    }
    

    使用您的 XML,此代码将输出

    &lt;chkr id=3&gt; 包含标签&lt;foo&gt; 2 次。

    编辑:如果您想要评论中指定的结果,只需将您的代码更改为以下内容:

    List<string> names = new List<string>();
    List<int> counts = new List<int>();
    
    foreach (var e in x.Descendants("chkr"))
    {
        names = new List<string>();
        counts = new List<int>();
    
        foreach (var v in e.Descendants().Where(ee => ee.Name != "ab" && ee.Name != "tt").GroupBy(ee => ee.Name).Select(ee => new { Name = ee.Key, Count = ee.Count() }))
        {
            if (v.Count > 1)
            {
                names.Add(v.Name.ToString());
                counts.Add(v.Count);
            }
        }
    
        if (names.Any())
            Console.WriteLine($"<chkr id={e.Attribute("id").Value}> contains the tag/tags {String.Join(",", names)} {String.Join(",", counts)} times.");
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多