Specify the number of equal lines in the XML file

I am wondering if there is a way to check how many equal lines are in the XML file. For example, this is an XML file:

<Root>
  <task>
    <sub1>test</sub1>
    <sub2>hello</sub2>
    <sub3>csharp</sub3>
  </task>
  <task>
    <sub1>test2</sub1>
    <sub2>hello2</sub2>
    <sub3>csharp2</sub3>
  </task>
  <task>
    <sub1>test3</sub1>
    <sub2>hello3</sub2>
    <sub3>csharp3</sub3>
  </task>
  <task>
    <sub1>test</sub1>
    <sub2>hello4</sub2>
    <sub3>csharp4</sub3>
  </task>
</Root>

As you can see, node.Innertext = "test"exists twice. I am wondering how can I read this? I tried something like

client["sub1"].InnerText.Count

but this counts the number of characters in this line.

Suggestions appreciated :)

EDIT: I am parsing an XML file usingXmlDocument

+4
source share
2 answers

Select the elements you want to check (for example, all sub-elements of all tasks) and group them by value:

xdoc.Root.Elements("task").SelectMany(t => t.Elements())
    .GroupBy(e => e.Value)
    .Select(g => new { Text = g.Key, Count = g.Count() })

Request syntax:

var xdoc = XDocument.Load(path_to_xml);
var result = from t in xdoc.Root.Elements("task")
             from e in t.Elements()
             group e by e.Value into g
             select new {
                  Text = g.Key,
                  Count = g.Count()
             };

With XPath:

var result = from e in xdoc.XPathSelectElements("//task/*")
             group e by e.Value into g
             select new {
                 Text = g.Key,
                 Count = g.Count()
             };

For your xml sample, the result will be:

[
  { Text: "test", Count: 2 },
  { Text: "hello", Count: 1 },
  { Text: "csharp", Count: 1 },
  { Text: "test2", Count: 1 },
  { Text: "hello2", Count: 1 },
  { Text: "csharp2", Count: 1 },
  { Text: "test3", Count: 1 },
  { Text: "hello3", Count: 1 },
  { Text: "csharp3", Count: 1 },
  { Text: "hello4", Count: 1 },
  { Text: "csharp4", Count: 1 }
]

, , :

 result.Where(x => x.Count > 1)

XmlDocument:

var doc = new XmlDocument();
doc.Load(path_to_xml);
var result = from XmlNode n in doc.SelectNodes("//task/*")
             group n by n.InnerText into g
             select new {
                 Text = g.Key,
                 Count = g.Count()
             };
+8
var dubs = XDocument.Parse(xml)
            .Descendants("task")
            .GroupBy(g => (string)g.Attribute("sub1"))
            .Where(g => g.Count() > 1)
            .Select(g => g.Key);
+1

Source: https://habr.com/ru/post/1539899/


All Articles