https://stackoverflow.com/questions/38425140/read-mulitple-childs-and-extract-data-xmlreader-in-c-sharp

CSharp · Console

/Program.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Xml.Serialization;
using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;
using System.IO;
using System.Data;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO.Compression;
using System.Reflection;

using NUnit.Framework; //NUnit.Framework.AssertionException

using Debug = System.Console;

    // https://stackoverflow.com/questions/38425140/read-mulitple-childs-and-extract-data-xmlreader-in-c-sharp
    public static partial class XmlReaderExtensions
    {
        public static IEnumerable<string> ReadAllElementContentsAsString(this XmlReader reader, string localName, string namespaceURI)
        {
            while (reader.ReadToFollowing(localName, namespaceURI))
                yield return reader.ReadElementContentAsString();
        }
		
        public static IEnumerable<XmlReader> ReadAllSubtrees(this XmlReader reader, string localName, string namespaceURI)
        {
            while (reader.ReadToFollowing(localName, namespaceURI))
                using (var subReader = reader.ReadSubtree())
                    yield return subReader;
        }
    }

    public static class TestClass
    {
        static string GetXml()
        {
            var xml = @"<Root>
<InformationTuples>
      <InformationTuple>
       <Name>documentClass</Name>
        <value format="""" valueset=""{rechnung}"" originalValue=""Rechnung"" start=""0"" end=""0"" LD=""0"" doc=""C:\b4enviam-service-test\inputDir\031a0933-2616-4d8e-8a79-56746ae0e160/Invoice_51029062.pdf"">Rechnung</value>
        <EntityType>Class</EntityType>
        <state>New       </state>
        <need>Mandatory </need>
        <extractionmethod>
        </extractionmethod>
        <weight>1</weight>
        <precondition type=""optional"">All</precondition>
      </InformationTuple>
      <InformationTuple>
        <Name>SAPNr.</Name>
        <value format="""" valueset="""" originalValue=""4352020616"" start=""0"" end=""0"" LD=""0"" doc=""C:\b4enviam-service-test\inputDir\031a0933-2616-4d8e-8a79-56746ae0e160/Invoice_51029062.pdf"">4352020616</value>
        <EntityType>KB.GTInovice</EntityType>
        <state>New       </state>
        <need>Mandatory </need>
        <extractionmethod>
        </extractionmethod>
        <weight>1</weight>
        <precondition type=""optional"">all</precondition>
      </InformationTuple>
      <InformationTuple>
        <Name>GT-Invoice</Name>
        <value format="""" valueset="""" originalValue="""" start=""0"" end=""0"" LD=""0"" doc="""">
        </value>
        <EntityType>KB.GTInovice</EntityType>
        <state>New       </state>
        <need>Mandatory </need>
        <extractionmethod>
        </extractionmethod>
        <weight>1</weight>
        <precondition type=""optional"">all</precondition>
      </InformationTuple>
    </InformationTuples>
<Unrelated>
      <InformationTuple>
       <Name>Should Not See Me For Nested Read</Name>
        <value format="""" valueset=""{rechnung}"" originalValue=""Rechnung"" start=""0"" end=""0"" LD=""0"" doc=""C:\b4enviam-service-test\inputDir\031a0933-2616-4d8e-8a79-56746ae0e160/Invoice_51029062.pdf"">Rechnung</value>
        <EntityType>Class</EntityType>
        <state>New       </state>
        <need>Mandatory </need>
        <extractionmethod>
        </extractionmethod>
        <weight>1</weight>
        <precondition type=""optional"">All</precondition>
      </InformationTuple>
</Unrelated>
</Root>";
            return xml;
        }

        public static void Test()
        {
            var xml = GetXml();
            var xmlNoSpace = XElement.Parse(xml).ToString(SaveOptions.DisableFormatting);
            var xmlWithSpace = XElement.Parse(xml).ToString(SaveOptions.None);

			Console.WriteLine("\nTesting original XML:");
            Test(xml);

			Console.WriteLine("\nTesting XML without whitespace:");
            Test(xmlNoSpace);

			Console.WriteLine("\nTesting XML with whitespace:");
            Test(xmlWithSpace);
			
			Console.WriteLine("Tests passed.");
        }

        private static void Test(string xml)
        {
            Debug.WriteLine("Simple read:");

            var list1 = new List<string>();
            
            using (var textReader = new StringReader(xml))
            using (var reader = XmlReader.Create(textReader))
            {
                foreach (var name in reader.ReadAllSubtrees("InformationTuple", "")
                    .Select(r => r.ReadAllElementContentsAsString("Name", "").First()))
                {
                    // Process the name somehow
                    Debug.WriteLine("  " + name);
                    list1.Add(name);
                }
            }

            Assert.IsTrue(XElement.Parse(xml).XPathSelectElements("//InformationTuple//Name").Select(e => e.Value).SequenceEqual(list1));

			var list2 = new List<string>();

            Debug.WriteLine("Read, <Name> optional:");

            using (var textReader = new StringReader(xml))
            using (var reader = XmlReader.Create(textReader))
            {
                foreach (var name in reader.ReadAllSubtrees("InformationTuple", "")
                    .SelectMany(r => r.ReadAllElementContentsAsString("Name", "").Take(1)))
                {
                    // Process the name somehow
                    Debug.WriteLine("  " + name);
                    list2.Add(name);
                }
            }
			
			Assert.IsTrue(list2.SequenceEqual(list1));
			
            Debug.WriteLine("Read all names:");
			
            var list3 = new List<string>();
			
            using (var textReader = new StringReader(xml))
            using (var reader = XmlReader.Create(textReader))
            {
                foreach (var name in reader.ReadAllSubtrees("InformationTuple", "")
                    .SelectMany(r => r.ReadAllElementContentsAsString("Name", "")))
                {
                    // Process the name somehow
                    Debug.WriteLine("  " + name);
                    list3.Add(name);
                }
            }
			
			Assert.IsTrue(list3.SequenceEqual(list1));
			
            Debug.WriteLine("Nested Read:");

            var list4 = new List<string>();

            using (var textReader = new StringReader(xml))
            using (var reader = XmlReader.Create(textReader))
            {
                foreach (var name in reader.ReadAllSubtrees("InformationTuples", "")
                    .SelectMany(r => r.ReadAllSubtrees("InformationTuple", ""))
                    .Select(r => r.ReadAllElementContentsAsString("Name", "").First()))
                {
                    // Process the name somehow
                    Debug.WriteLine("  " + name);
                    list4.Add(name);
                }
            }

            Assert.IsTrue(XElement.Parse(xml).XPathSelectElements("//InformationTuples//InformationTuple//Name").Select(e => e.Value).SequenceEqual(list4));

            Debug.WriteLine("done.");
        }
    }

	public class Program
	{
		public static void Main()
		{
			Console.WriteLine("Environment version: {0} ({1})", System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription , GetNetCoreVersion());
			Console.WriteLine();

			try
			{
				TestClass.Test();
			}
			catch (Exception ex)
			{
				Console.WriteLine("Failed with unhandled exception: ");
				Console.WriteLine(ex);
				throw;
			}
		}
		
		public static string GetNetCoreVersion()
		{
			//https://techblog.dorogin.com/how-to-detect-net-core-version-in-runtime-ecd65ad695be
			//
			var assembly = typeof(System.Runtime.GCSettings).GetTypeInfo().Assembly;
			var assemblyPath = assembly.CodeBase.Split(new[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries);
			int netCoreAppIndex = Array.IndexOf(assemblyPath, "Microsoft.NETCore.App");
			if (netCoreAppIndex > 0 && netCoreAppIndex < assemblyPath.Length - 2)
				return assemblyPath[netCoreAppIndex + 1];
			return null;
		}
	}
;