
using System;
using System.Xml;
using System.IO;
using System.Collections.Generic;
using DataContracts;
using System.Text.RegularExpressions;
using System.Reflection;
using System.Linq;
using System.Xml.Schema;
using System.Text;

namespace Ato.EN.IntegrationServices.CodeGenerationDISTBENTRT
{
    /// <summary>
    /// XML Consumer for DISTBENTRT
    /// </summary>
    public class DISTBENTRT2024XmlConsumer
    {
        const string MissingMandatoryMessage = "A mandatory field has not been completed.";
        const string ContactYourProviderMsg = "The message did not pass XML validation. Please contact your software provider.";
        const string InvalidDataValidation = "A field contains invalid data (such as letters in numeric or date field).";
        private const string ErrorCode1 = "CMN.ATO.GEN.XML01";
        private const string ErrorCode3 = "CMN.ATO.GEN.XML03";
        private const string ErrorCode4 = "CMN.ATO.GEN.XML04";
        private const string ErrorCode6 = "CMN.ATO.GEN.XML06";
        private bool _found = false;
        private int _parentCollectionCount;
        private int _childCollectionCount;
        private bool _isExiting = false;
        private bool _isValidationError = false;
        private string _lastPath = string.Empty;
        private ErrorMessageType _validationError = new ErrorMessageType(ErrorDescriptor.NoError);


        #region Error Messages

        public List<ProcessMessageDocument> ErrorMessages { get; set; }

        public bool HasErrors
        {
            get
            {
                return ErrorMessages != null && ErrorMessages.Count > 0;
            }
        }

        private string GetCurrentLocation()
        {
            StringBuilder location = new StringBuilder();
            string[] paths = _currentXPath.ToArray<string>();
            for (int i = paths.Length - 1; i > -1; i--)
            {
                location.Append(paths[i]);
            }
            return location.ToString();
        }

        private void MissingElementError()
        {
            ProcessMessageDocument processMessage;
            processMessage = new ProcessMessageDocument()
            {
                Code = "CMN.ATO.GEN.XML04",
                Description = MissingMandatoryMessage,
                SeverityAsString = "Error",
                Location = GetCurrentLocation(),
            };
            this.ErrorMessages.Add(processMessage);
        }

        #endregion  Error Messages

        #region Embedded Schema

        private static readonly XmlSchemaSet EmbeddedXmlSchemaSet;
        static DISTBENTRT2024XmlConsumer()
        {
            Assembly executingAssembly = Assembly.GetExecutingAssembly();
            string[] manifestResourceNames = executingAssembly.GetManifestResourceNames();
            string resourceName;
            Stream embeddedSchemaStream;
            XmlSchema embeddedXmlSchema;

            if (manifestResourceNames != null)
            {
                resourceName = manifestResourceNames.FirstOrDefault(rn => rn.Contains("ato.distbentrt.0001.2024.01.00.xsd") && rn.EndsWith(".xsd"));
                if (resourceName != null)
                {
                    embeddedSchemaStream = executingAssembly.GetManifestResourceStream(resourceName);
                    embeddedXmlSchema = XmlSchema.Read(embeddedSchemaStream, SchemaCallback);
                    EmbeddedXmlSchemaSet = new XmlSchemaSet();
                    EmbeddedXmlSchemaSet.Add(embeddedXmlSchema);
                    EmbeddedXmlSchemaSet.Compile();
                }
            }
        }

        private static void SchemaCallback(object sender, ValidationEventArgs args)
        {
            if (args.Severity == XmlSeverityType.Error)
                throw new XmlSchemaException(args.Message);
        }

        #endregion  Embedded Schema

        #region Xml Reader Settings

        private static XmlReaderSettings ReaderSettings = new XmlReaderSettings()
        {
            CloseInput = false,
            ConformanceLevel = ConformanceLevel.Fragment,
            IgnoreWhitespace = true,
            IgnoreComments = true,
            IgnoreProcessingInstructions = true,
        };

        private XmlReaderSettings GetValidatingReaderSettings()
        {
            XmlReaderSettings validatingReaderSettings = new XmlReaderSettings()
            {
                CloseInput = false,
                ConformanceLevel = ConformanceLevel.Fragment,
                IgnoreWhitespace = true,
                IgnoreComments = true,
                IgnoreProcessingInstructions = true,
                ValidationType = ValidationType.Schema,
            };
            if (EmbeddedXmlSchemaSet == null)
            {
                throw new XmlSchemaException("Embedded Schema is Null");
            }
            else
            {
                validatingReaderSettings.Schemas.Add(EmbeddedXmlSchemaSet);
                validatingReaderSettings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);
            }
            return validatingReaderSettings;
        }

        private static Regex DataTypeFailureExpression = new Regex("'(?<Uniqueid>.*?)' element is invalid.*value '(?<Value>.*?)' is invalid.*datatype '(?<DataType>.*?)'", RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.Singleline);

        private void ValidationCallBack(object sender, ValidationEventArgs args)
        {
            var msg = args.Message;
            var msgToLower = msg.ToLower();

            ProcessMessageDocument processMessage = null;
  
            if (msgToLower.Contains("invalid according to its datatype"))
            {
                Match match = DataTypeFailureExpression.Match(args.Message);

                if (match.Success && match.Groups.Count == 4)
                {
                    var inner = args.Exception.InnerException;
                    var hint = (inner != null && !string.IsNullOrEmpty(inner.Message)) ? " Hint: " + inner.Message : string.Empty;
                    processMessage = BuildProcessMessageDocument(InvalidDataValidation, string.Empty, ErrorCode3);

                    string uniqueID = match.Groups["Uniqueid"].Value;
                    string value = match.Groups["Value"].Value;
                    string dataType = match.Groups["DataType"].Value;


                    var longDescription = string.Format(@"The value specified for an item does not match the item type (value = ""{0}"", item type = {1}, uniqueID = {2})", value, dataType, uniqueID);
                    processMessage.LongDescription = longDescription + hint;
                    processMessage.Parameters = new ProcessMessageParameters();
                    processMessage.Parameters.Add(new ProcessMessageParameter() { Name = "uniqueID", Value = uniqueID });
                    processMessage.Parameters.Add(new ProcessMessageParameter() { Name = "value", Value = value });
                    processMessage.Parameters.Add(new ProcessMessageParameter() { Name = "dataType", Value = dataType });
                }
            }
            else if (msgToLower.Contains("has incomplete content"))
            {
                _validationError = GetErrorDescriptorForHasIncompleteContent(msg);
                processMessage = BuildProcessMessageDocument(MissingMandatoryMessage, msg + _validationError.Hint, _validationError.Code);
                _isValidationError = true;
            }
            else if (msgToLower.Contains("has invalid child element"))
            {
                _validationError = GetErrorDescriptorForHasInvalidChildElement(msg);
                var shortMessage = _validationError.Code == ErrorCode4 ? MissingMandatoryMessage : ContactYourProviderMsg;
                processMessage = BuildProcessMessageDocument(shortMessage, msg + _validationError.Hint, _validationError.Code);
                _isValidationError = true;
            }
            else
            {
                processMessage = BuildProcessMessageDocument(ContactYourProviderMsg, msg, ErrorCode1);
                _isValidationError = true;
            }

            this.ErrorMessages.Add(processMessage);
        }

        private ProcessMessageDocument BuildProcessMessageDocument(string shortDescription, string longDescription, string code)
        {
            return new ProcessMessageDocument()
            {
                Code = code,
                Description = shortDescription,
                LongDescription = longDescription,
                SeverityAsString = "Error",
                Location = GetCurrentLocation()
            };
        }

        private ProcessMessageDocument BuildProcessMessageDocument(ProcessMessageDocument processMessage, string newLocation)
        {
            return new ProcessMessageDocument()
            {
                Code = processMessage.Code,
                Description = processMessage.Description,
                LongDescription = processMessage.LongDescription,
                SeverityAsString = "Error",
                Location = newLocation
            };
        }

        private enum ErrorDescriptor
        {
            NoError = 0,
            MandatoryElementError,
            NonMandatoryElementError,
            UnknownElement,
            Duplicate
        }

        private struct ErrorMessageType
        {
            public string Hint, Code, ExpectedNextValidElement;
            public ErrorDescriptor Errno;

            public ErrorMessageType(ErrorDescriptor errorDescriptor)
            {
                Errno = errorDescriptor;
                Hint = "";
                Code = "";
                ExpectedNextValidElement = "";
            }

            public ErrorMessageType(ErrorDescriptor errorDescriptor, string hint, string code, string elementName)
            {
                Errno = errorDescriptor;
                Hint = hint;
                Code = code;
                ExpectedNextValidElement = elementName;
            }
        }

        private ErrorMessageType GetErrorDescriptorForHasIncompleteContent(string validationErrorMessage)
        {
            ErrorMessageType retval = new ErrorMessageType();
            if (string.IsNullOrWhiteSpace(validationErrorMessage)) return retval;

            validationErrorMessage = validationErrorMessage.Replace(" ", string.Empty);
            validationErrorMessage = validationErrorMessage.Replace("'", " ");
            var parts = validationErrorMessage.Split(' ');
            if (parts.Length != 9) return retval;

            var elementBeingProcessed = parts[1];
            var csvList = parts[5];

            retval = ParseHasIncompleteContentCVSList(csvList, elementBeingProcessed);
            return retval;
        }

        private ErrorMessageType GetErrorDescriptorForHasInvalidChildElement(string validationErrorMessage)
        {
            string msg = string.Empty;
            ErrorMessageType retval = new ErrorMessageType();
            if (string.IsNullOrWhiteSpace(validationErrorMessage)) return retval;

            validationErrorMessage = validationErrorMessage.Replace(" ", string.Empty);
            validationErrorMessage = validationErrorMessage.Replace("'", " ");
            var parts = validationErrorMessage.Split(' ');

            //decide which message format to process
            if (validationErrorMessage.ToLower().Contains("listofpossibleelements"))
            {
                if (parts.Length == 13 || parts.Length == 12 || parts.Length == 10)
                {
                    var csvList = parts[9];
                    var elementBeingProcessed = parts[1];
                    var invalidChildElementName = parts[5];
                    retval = ParseCvsListForHasInvalidChildElementLongFormat(csvList, invalidChildElementName, elementBeingProcessed);
                }

                return retval;
            }
            else
            {
                if (parts.Length != 9) return retval;
                var csvList = parts[5];
                var elementBeingProcessed = parts[1];
                var invalidChildElementName = parts[5];
                
                retval = ParseCvsListForHasInvalidChildElementLongFormat(csvList, invalidChildElementName, elementBeingProcessed);
            }
            return retval;
        }

        private ErrorMessageType ParseCvsListForHasInvalidChildElementShortFormat(string csvList, string invalidChildElementName, string elementBeingProcessed)
        {
            ErrorMessageType retval = new ErrorMessageType();

            if (!string.IsNullOrEmpty(csvList))
            {
                var lastElementInListOfPossibleElements = GetLastElementInCsvList(csvList);

                retval.Hint =
                    string.Format(
                        " Hint: while processing parent element [{0}] child element [{1}] was unexpected",
                        elementBeingProcessed, invalidChildElementName);
                retval.Code = ErrorCode1;
                retval.Errno = ErrorDescriptor.UnknownElement;
                retval.ExpectedNextValidElement = invalidChildElementName;
            }

            return retval;
        }

        private string GetLastElementInCsvList(string csvList)
        {
            var list = (csvList.Contains(','))
                ? new List<string>(csvList.Split(','))
                : new List<string> { csvList };

            string lastElement = list.Last();        
            if (lastElement.EndsWith("...."))
            {
                list.RemoveAt(list.Count-1);
            }

            return list.Last();
        }

        private ErrorMessageType ParseCvsListForHasInvalidChildElementLongFormat(string csvList, string invalidChildElementName, string elementBeingProcessed)
        {
            ErrorMessageType retval = new ErrorMessageType();

            if (!string.IsNullOrEmpty(csvList))
            {
                var lastElementInListOfPossibleElements = GetLastElementInCsvList(csvList);
                var elementList = new List<string>(_elementCsvList.Split(','));

                if (ContainsElementForElementBeingProcessed(elementList, elementBeingProcessed, invalidChildElementName))
                {
                    var indexOfElementBeingProcessed = GetIndexOfElementBeingProcessed(elementList, elementBeingProcessed);
                    var indexOfinvalidChildElementName = GetIndexOfElementUnderElementBeingProcessed(elementList, elementBeingProcessed, invalidChildElementName);
                    var indexOflastElementInListOfPossibleElements = GetIndexOfElementUnderElementBeingProcessed(elementList, elementBeingProcessed, lastElementInListOfPossibleElements);

                    if (indexOfinvalidChildElementName > indexOflastElementInListOfPossibleElements) 
                    {
                        retval.Hint =
                            string.Format(
                                " Hint: while processing parent element [{0}] child mandatory element [{1}] was expected but not found",
                                elementBeingProcessed, lastElementInListOfPossibleElements);
                        retval.Code = ErrorCode4;
                        retval.Errno = ErrorDescriptor.MandatoryElementError;
                        retval.ExpectedNextValidElement = lastElementInListOfPossibleElements;
                    }
                    else
                    {
                        retval.Hint =
                            string.Format(
                                " Hint: while processing parent element [{0}] child non mandatory element [{1}] was unexpected",
                                elementBeingProcessed, invalidChildElementName);
                        retval.Code = ErrorCode1;
                        retval.Errno = (indexOfinvalidChildElementName != indexOflastElementInListOfPossibleElements) ? ErrorDescriptor.NonMandatoryElementError : ErrorDescriptor.Duplicate;
                        retval.ExpectedNextValidElement = invalidChildElementName;
                    }
                }
                else
                {
                    //this element is unknown to the schema.
                    retval.Hint =
                        string.Format(
                            " Hint: while processing parent element [{0}] child element [{1}] was unexpected",
                            elementBeingProcessed, invalidChildElementName);
                    retval.Code = ErrorCode1;
                    retval.Errno = ErrorDescriptor.UnknownElement;
                    retval.ExpectedNextValidElement = invalidChildElementName;
                }
            }

            return retval;
        }

        private int GetIndexOfElementUnderElementBeingProcessed(List<string> validElementList,
                                                                string elementBeingProcessed,
                                                                string elementName)
        {
            int result;

            string elementWithParentNameMatch = elementBeingProcessed + "#" + elementName;
            result = validElementList.IndexOf(elementWithParentNameMatch);

            if (result < 0)
            {
                result = validElementList.IndexOf(elementName);
            }

            return result;
        }

        private int GetIndexOfElementBeingProcessed(List<string> validElementList,
                                                    string elementBeingProcessed)
        {
           return validElementList.IndexOf(elementBeingProcessed);
        }

        private bool ContainsElementForElementBeingProcessed(List<string> validElementList,
                                                             string elementBeingProcessed,
                                                             string elementName)
        {
            return validElementList.Contains(elementBeingProcessed + "#" + elementName) || validElementList.Contains(elementName);
        }

        private ErrorMessageType ParseHasIncompleteContentCVSList(string csvList, string elementBeingProcessed)
        {
            ErrorMessageType retval = new ErrorMessageType();

            if (!string.IsNullOrEmpty(csvList))
            {
                var lastElementInListOfPossibleElements = GetLastElementInCsvList(csvList);

                retval.Hint =
                    string.Format(
                        " Hint: while processing parent element [{0}] child mandatory element [{1}] was not found",
                        elementBeingProcessed, lastElementInListOfPossibleElements);

                retval.Code = ErrorCode4;
                retval.Errno = ErrorDescriptor.MandatoryElementError;
                retval.ExpectedNextValidElement = lastElementInListOfPossibleElements;
            }
            return retval;
        }

        private void StartEndDateError(DateTime startDate, DateTime endDate)
        {
            ProcessMessageDocument processMessage;

            string longDescription = string.Format("End date is earlier than start date (state date = {0}, end date = {1})", startDate.ToString("yyyy-MM-dd"), endDate.ToString("yyyy-MM-dd"));

            processMessage = new ProcessMessageDocument()
            {
                Code = "CMN.ATO.GEN.XML06",
                Description = "End date is earlier than start date.",
                LongDescription = longDescription,
                SeverityAsString = "Error",
                Location = GetCurrentLocation(),
            };
            processMessage.Parameters = new ProcessMessageParameters();
            processMessage.Parameters.Add(new ProcessMessageParameter() { Name = "startDate", Value = startDate.ToString("yyyy-MM-dd") });
            processMessage.Parameters.Add(new ProcessMessageParameter() { Name = "endDate", Value = endDate.ToString("yyyy-MM-dd") });
            this.ErrorMessages.Add(processMessage);
        }

        private void StartEndDateError(DateTime? startDate, DateTime? endDate)
        {
            ProcessMessageDocument processMessage;

            if (startDate == null || endDate == null)
                return;

            string longDescription = string.Format("End date is earlier than start date (state date = {0}, end date = {1})", startDate.Value.ToString("yyyy-MM-dd"), endDate.Value.ToString("yyyy-MM-dd"));

            processMessage = new ProcessMessageDocument()
            {
                Code = "CMN.ATO.GEN.XML06",
                Description = "End date is earlier than start date.",
                LongDescription = longDescription,
                SeverityAsString = "Error",
                Location = GetCurrentLocation(),
            };
            processMessage.Parameters = new ProcessMessageParameters();
            processMessage.Parameters.Add(new ProcessMessageParameter() { Name = "startDate", Value = startDate.Value.ToString("yyyy-MM-dd") });
            processMessage.Parameters.Add(new ProcessMessageParameter() { Name = "endDate", Value = endDate.Value.ToString("yyyy-MM-dd") });
            this.ErrorMessages.Add(processMessage);
        }

        #endregion  Xml Reader Settings

        #region IsEmptyOrNilElement
        private static bool IsEmptyOrNilElement(XmlReader reader)
        {
            bool emptyOrNil = false;
            if (reader.IsEmptyElement)
            {
                emptyOrNil = true;
            }
            else
            {
                if (reader.HasAttributes)
                {
                    string nilValue = reader.GetAttribute("nil", "http://www.w3.org/2001/XMLSchema-instance");
                    if (nilValue != null && nilValue.ToLowerInvariant() == "true" || nilValue == "1")
                    {
                        emptyOrNil = true;
                    }
                }
            }
            return emptyOrNil;
        }
        #endregion  IsEmptyOrNilElement

        #region ToBoolean
        private bool? ToBoolean(string str)
        {
            bool returnValue;
            string value = (str ?? "").Trim();
            if (value == "0" || value == "1")
                return Convert.ToBoolean(Convert.ToInt32(value));
            
            if (Boolean.TryParse(value, out returnValue))
                return returnValue;
            return null;
        }
        #endregion  ToBoolean

        #region MoveToContent
        public bool MoveToContent(XmlReader reader)
        {
            try
            {
                reader.MoveToContent();
                return true;
            }
            catch (XmlException ex)
            {
                ProcessMessageDocument processMessage;
                processMessage = new ProcessMessageDocument()
                {
                    Code = "CMN.ATO.GEN.XML01",
                    Description = ContactYourProviderMsg,
                    LongDescription = ex.Message,
                    SeverityAsString = "Error",
                };
                this.ErrorMessages.Add(processMessage);
                return false;
            }
        }
        #endregion  MoveToContent

        #region ReadToNextElement


        public bool ReadToNextElement(XmlReader reader, bool isMandatory) 
        {
            return ReadToNextElement(reader);
        }

        public bool ReadToNextElement(XmlReader reader) 
        {
            bool retval = false;

            if ( (reader.EOF && !_isValidationError) || _isExiting)
            {
                return false; //do nothing
            }

            if (!_isValidationError)
            {
                retval = SetReaderToNextElement(reader); //position the reader on the next valid element
            }

            if (_isValidationError)
            {
                //process validation errors
                var expectedNextElement = (!string.IsNullOrEmpty(_validationError.ExpectedNextValidElement)) ? _validationError.ExpectedNextValidElement : reader.LocalName;
                var actualNextValidElement = reader.LocalName;
                var location = GetCurrentLocation();

                if (_validationError.Errno == ErrorDescriptor.Duplicate)
                {
                    location = _lastPath;
                }

                var xpath = RemoveLeadingAndTrailingSlashes(location);

                var element = GetElementDescriptor(xpath);

                if (_validationError.Errno == ErrorDescriptor.UnknownElement)
                {
                    //set the xpath for elements that are not known to the schema
                    location = "/" + element.Path + "/" + element.Prefix + ":" + _validationError.ExpectedNextValidElement;
                    _isExiting = true;
                }
                else if(_validationError.Errno == ErrorDescriptor.NonMandatoryElementError)
                {
                    //set the xpath for the optional element that caused a validation
                    location = "/" + element.Path + "/" + element.Prefix + ":" + reader.LocalName;
                    _isExiting = true;
                }
                else
                {
                    //decide if we have spooled to the missing mandatory element. 
                    _isExiting = expectedNextElement == element.PathLeafNode;
                }

                if(_isExiting)
                {
                    //The location has changed since detection of the validation error - so update it.
                    UpdateErrorMessageWithLocation(location);
                }

                return false;
             }

             //Save previous path so we can detect duplicate elements
            _lastPath = GetCurrentLocation();

            return retval;
        }

        private bool ReadNext(XmlReader reader)
        {
            return !reader.EOF && reader.Read();
        }

        private void UpdateErrorMessageWithLocation(string newLocation)
        {
            var lastProcessMessage = ErrorMessages.Last();
            ErrorMessages.Remove(lastProcessMessage);
            var newProcessMessage = BuildProcessMessageDocument(lastProcessMessage, newLocation);
            ErrorMessages.Add(newProcessMessage);
        }

        private string RemoveLeadingAndTrailingSlashes(string xpath)
        {
            var xpathLength = xpath.Length;
            if (xpathLength <= 0) return string.Empty;
            var firstChar = xpath.Substring(0, 1);
            var lastChar = xpath.Substring(xpathLength - 1, 1);
            if (firstChar == "/")
            {
                xpath = xpath.Remove(0, 1);
                xpathLength--;
            }
            if (lastChar == "/")
            {
                xpath = xpath.Remove(xpathLength - 1, 1);
            }
            return xpath;
        }

        private struct ElementDescriptor
        {
            public string Prefix, PathLeafNode, Path;
            public ElementDescriptor(string prefix, string leaf , string path)
            {
                Prefix = prefix;
                PathLeafNode = leaf;
                Path = path;
            }
        }

        private ElementDescriptor GetElementDescriptor(string xpath)
        {
            var retval = new ElementDescriptor();

            var parts = xpath.Split('/');
            var numberOfParts = parts.Length;
            if (numberOfParts > 0)
            {
                var leafNode = parts[numberOfParts - 1];
                var p = leafNode.Split(':');
                numberOfParts = p.Length;
                if(numberOfParts == 1)
                {
                    retval.PathLeafNode = p[0];
                    retval.Prefix = string.Empty;
                }
                else if(numberOfParts == 2)
                {
                    retval.PathLeafNode = p[1];
                    retval.Prefix = p[0];
                }
                var leafNodeLength = leafNode.Length;
                var path = xpath.Remove(xpath.Length - leafNodeLength, leafNodeLength);
                retval.Path = RemoveLeadingAndTrailingSlashes(path);
            }
            return retval;
        }

        private bool SetReaderToNextElement(XmlReader reader) 
        {
            try
            {
                if (reader.EOF || _isExiting) return false;
                if (_found)
                {
                    reader.Read();
                    _found = false;
                }
                while (!reader.EOF && reader.NodeType != XmlNodeType.Element)
                {
                    reader.Read();
                }
      
                return reader.NodeType == XmlNodeType.Element && !reader.EOF;

            }
            catch (XmlException ex)
            {
                ProcessMessageDocument processMessage;
                processMessage = new ProcessMessageDocument()
                {
                    Code = ErrorCode1,
                    Description = ContactYourProviderMsg,
                    LongDescription = ex.Message,
                    SeverityAsString = "Error",
                };
                this.ErrorMessages.Add(processMessage);
                return false;
            }
        }

        #endregion  ReadToNextElement

        private Stack<string> _currentXPath = new Stack<string>();

        public DISTBENTRT2024 Consume(Stream streamToLoad, bool validateDataTypes = false)
        {
            DISTBENTRT2024 report = new DISTBENTRT2024();

            // Working Variable for if can still read from the xml stream
            bool reading;

            // Working Variables for current values
            string currentValue;
            DateTime currentDateTimeValue;
            bool? currentBooleanValue;
            decimal currentDecimalValue;
            double currentDoubleValue;
            float currentFloatValue;
            sbyte currentsByteValue;
            byte currentByteValue;
            short currentShortValue;
            ushort currentuShortValue;
            uint currentuIntValue;
            int currentIntValue;
            long currentLongValue;
            ulong currentuLongValue;

            this.ErrorMessages = new List<ProcessMessageDocument>();
            _currentXPath.Push("/tns:DISTBENTRT");

            if (streamToLoad == null || streamToLoad.Length == 0 || !streamToLoad.CanRead)
            {
                MissingElementError();
                return report;
            }

            streamToLoad.Position = 0;
            XmlReader reader;

            if (validateDataTypes)
                reader = XmlReader.Create(streamToLoad, GetValidatingReaderSettings());
            else
                reader = XmlReader.Create(streamToLoad, ReaderSettings);

            if (!MoveToContent(reader))
                return report;

            reading = !reader.EOF;

            if (ReadToNextElement(reader) && reader.LocalName == "DISTBENTRT" && reader.NamespaceURI == "http://www.sbr.gov.au/ato/distbentrt")
            {
                _found = true;
                ReadToNextElement(reader);
            }
            else
            {
                MissingElementError();
                return report;
            }

    
            #region RP
            _currentXPath.Push("/tns:RP");
            //3. use case
            if (ReadToNextElement(reader,true) && reader.LocalName == "RP")
            {
                report.RpCollectionExists = true;
                report.RpCollectionCount += 1;
                _found = true; 
        
                #region PeriodStartD
                _currentXPath.Push("/tns:PeriodStartD");
                //6. use case
                if (ReadToNextElement(reader,true) && reader.LocalName == "PeriodStartD")
                {
                    if (!IsEmptyOrNilElement(reader))
                    {
                        ReadNext(reader);
                        if (reader.NodeType == XmlNodeType.Text || reader.NodeType == XmlNodeType.CDATA)
                        {
                            currentValue = reader.Value;
                            ReadNext(reader); // consume the end element so we detect any validation errors before _currentXPath is updated.
                            if (DateTime.TryParse(currentValue, out currentDateTimeValue))
                            {
                                report.DISTBENTRT1 = currentDateTimeValue.Date;
                            }
                        }
                    }
                    _found = true;
                }
        
                _currentXPath.Pop();
                #endregion PeriodStartD
        
                #region PeriodEndD
                _currentXPath.Push("/tns:PeriodEndD");
                //6. use case
                if (ReadToNextElement(reader,true) && reader.LocalName == "PeriodEndD")
                {
                    if (!IsEmptyOrNilElement(reader))
                    {
                        ReadNext(reader);
                        if (reader.NodeType == XmlNodeType.Text || reader.NodeType == XmlNodeType.CDATA)
                        {
                            currentValue = reader.Value;
                            ReadNext(reader); // consume the end element so we detect any validation errors before _currentXPath is updated.
                            if (DateTime.TryParse(currentValue, out currentDateTimeValue))
                            {
                                report.DISTBENTRT2 = currentDateTimeValue.Date;
                            }
                        }
                    }
                    _found = true;
                }
        
                _currentXPath.Pop();
                #endregion PeriodEndD
        
                #region TaxFileNumberId
                _currentXPath.Push("/tns:TaxFileNumberId");
                //6. use case
                if (ReadToNextElement(reader,true) && reader.LocalName == "TaxFileNumberId")
                {
                    if (!IsEmptyOrNilElement(reader))
                    {
                        ReadNext(reader);
                        if (reader.NodeType == XmlNodeType.Text || reader.NodeType == XmlNodeType.CDATA)
                        {
                            currentValue = reader.Value;
                            ReadNext(reader); // consume the end element so we detect any validation errors before _currentXPath is updated.
                            report.DISTBENTRT3 = currentValue;
                        }
                    }
                    _found = true;
                }
        
                _currentXPath.Pop();
                #endregion TaxFileNumberId
        
                #region StatementOfDistributionToBeneficiary
        
                _currentXPath.Push("/tns:StatementOfDistributionToBeneficiaryCollection");
                // 4. use case
                if (ReadToNextElement(reader,false) && reader.LocalName == "StatementOfDistributionToBeneficiaryCollection")
                {
                    report.RP_StatementOfDistributionToBeneficiaryCollection = new List<DISTBENTRT2024.RP_StatementOfDistributionToBeneficiary>();
                    report.RP_StatementOfDistributionToBeneficiaryCollectionExists = true;
        
                    _found = true;
        
                    while ( ReadToNextElement(reader,false) && reader.LocalName == "StatementOfDistributionToBeneficiary" ) 
                    {
                        _found = true;
        
                        DISTBENTRT2024.RP_StatementOfDistributionToBeneficiary statementOfDistributionToBeneficiary = new DISTBENTRT2024.RP_StatementOfDistributionToBeneficiary();
                        report.RP_StatementOfDistributionToBeneficiaryCollection.Add(statementOfDistributionToBeneficiary);
                        report.RP_StatementOfDistributionToBeneficiaryCollectionCount += 1;
                        statementOfDistributionToBeneficiary.OccurrenceIndex = report.RP_StatementOfDistributionToBeneficiaryCollectionCount;
        
                        _currentXPath.Push("/tns:StatementOfDistributionToBeneficiary[" + report.RP_StatementOfDistributionToBeneficiaryCollectionCount + "]");
                
                        #region DistributingTrust
                        _currentXPath.Push("/tns:DistributingTrust");
                        //3. use case
                        if (ReadToNextElement(reader,true) && reader.LocalName == "DistributingTrust")
                        {
                            statementOfDistributionToBeneficiary.RP_StatementOfDistributionToBeneficiary_DistributingTrustCollectionExists = true;
                            statementOfDistributionToBeneficiary.RP_StatementOfDistributionToBeneficiary_DistributingTrustCollectionCount += 1;
                            _found = true; 
                    
                            #region AustralianBusinessNumberId
                            _currentXPath.Push("/tns:AustralianBusinessNumberId");
                            //6. use case
                            if (ReadToNextElement(reader,false) && reader.LocalName == "AustralianBusinessNumberId")
                            {
                                if (!IsEmptyOrNilElement(reader))
                                {
                                    ReadNext(reader);
                                    if (reader.NodeType == XmlNodeType.Text || reader.NodeType == XmlNodeType.CDATA)
                                    {
                                        currentValue = reader.Value;
                                        ReadNext(reader); // consume the end element so we detect any validation errors before _currentXPath is updated.
                                        statementOfDistributionToBeneficiary.DISTBENTRT4 = currentValue;
                                    }
                                }
                                _found = true;
                            }
                    
                            _currentXPath.Pop();
                            #endregion AustralianBusinessNumberId
                    
                            #region AustralianCompanyNumberId
                            _currentXPath.Push("/tns:AustralianCompanyNumberId");
                            //6. use case
                            if (ReadToNextElement(reader,false) && reader.LocalName == "AustralianCompanyNumberId")
                            {
                                if (!IsEmptyOrNilElement(reader))
                                {
                                    ReadNext(reader);
                                    if (reader.NodeType == XmlNodeType.Text || reader.NodeType == XmlNodeType.CDATA)
                                    {
                                        currentValue = reader.Value;
                                        ReadNext(reader); // consume the end element so we detect any validation errors before _currentXPath is updated.
                                        statementOfDistributionToBeneficiary.DISTBENTRT41 = currentValue;
                                    }
                                }
                                _found = true;
                            }
                    
                            _currentXPath.Pop();
                            #endregion AustralianCompanyNumberId
                    
                            #region MiscellaneousInvestorReferenceNumberId
                            _currentXPath.Push("/tns:MiscellaneousInvestorReferenceNumberId");
                            //6. use case
                            if (ReadToNextElement(reader,false) && reader.LocalName == "MiscellaneousInvestorReferenceNumberId")
                            {
                                if (!IsEmptyOrNilElement(reader))
                                {
                                    ReadNext(reader);
                                    if (reader.NodeType == XmlNodeType.Text || reader.NodeType == XmlNodeType.CDATA)
                                    {
                                        currentValue = reader.Value;
                                        ReadNext(reader); // consume the end element so we detect any validation errors before _currentXPath is updated.
                                        statementOfDistributionToBeneficiary.DISTBENTRT42 = currentValue;
                                    }
                                }
                                _found = true;
                            }
                    
                            _currentXPath.Pop();
                            #endregion MiscellaneousInvestorReferenceNumberId
                    
                            #region OrganisationNameDetailsOrganisationalNameT
                            _currentXPath.Push("/tns:OrganisationNameDetailsOrganisationalNameT");
                            //6. use case
                            if (ReadToNextElement(reader,true) && reader.LocalName == "OrganisationNameDetailsOrganisationalNameT")
                            {
                                if (!IsEmptyOrNilElement(reader))
                                {
                                    ReadNext(reader);
                                    if (reader.NodeType == XmlNodeType.Text || reader.NodeType == XmlNodeType.CDATA)
                                    {
                                        currentValue = reader.Value;
                                        ReadNext(reader); // consume the end element so we detect any validation errors before _currentXPath is updated.
                                        statementOfDistributionToBeneficiary.DISTBENTRT5 = currentValue;
                                    }
                                }
                                _found = true;
                            }
                    
                            _currentXPath.Pop();
                            #endregion OrganisationNameDetailsOrganisationalNameT
                        } // End of if DistributingTrust node exists
                
                        _currentXPath.Pop();
                        #endregion DistributingTrust
                
                        #region Information
                        _currentXPath.Push("/tns:Information");
                        //3. use case
                        if (ReadToNextElement(reader,false) && reader.LocalName == "Information")
                        {
                            statementOfDistributionToBeneficiary.RP_StatementOfDistributionToBeneficiary_InformationCollectionExists = true;
                            statementOfDistributionToBeneficiary.RP_StatementOfDistributionToBeneficiary_InformationCollectionCount += 1;
                            _found = true; 
                    
                            #region IncomeTrustEstateIncomeShareA
                            _currentXPath.Push("/tns:IncomeTrustEstateIncomeShareA");
                            //6. use case
                            if (ReadToNextElement(reader,false) && reader.LocalName == "IncomeTrustEstateIncomeShareA")
                            {
                                if (!IsEmptyOrNilElement(reader))
                                {
                                    ReadNext(reader);
                                    if (reader.NodeType == XmlNodeType.Text || reader.NodeType == XmlNodeType.CDATA)
                                    {
                                        currentValue = reader.Value;
                                        ReadNext(reader); // consume the end element so we detect any validation errors before _currentXPath is updated.
                                        if (Decimal.TryParse(currentValue, out currentDecimalValue))
                                        {
                                            statementOfDistributionToBeneficiary.DISTBENTRT6 = currentDecimalValue;
                                        }
                                    }
                                }
                                _found = true;
                            }
                    
                            _currentXPath.Pop();
                            #endregion IncomeTrustEstateIncomeShareA
                    
                            #region IncomeTaxPayAsYouGoWithholdingCreditForAmountsWithheldFromForeignResidentsA
                            _currentXPath.Push("/tns:IncomeTaxPayAsYouGoWithholdingCreditForAmountsWithheldFromForeignResidentsA");
                            //6. use case
                            if (ReadToNextElement(reader,false) && reader.LocalName == "IncomeTaxPayAsYouGoWithholdingCreditForAmountsWithheldFromForeignResidentsA")
                            {
                                if (!IsEmptyOrNilElement(reader))
                                {
                                    ReadNext(reader);
                                    if (reader.NodeType == XmlNodeType.Text || reader.NodeType == XmlNodeType.CDATA)
                                    {
                                        currentValue = reader.Value;
                                        ReadNext(reader); // consume the end element so we detect any validation errors before _currentXPath is updated.
                                        if (Decimal.TryParse(currentValue, out currentDecimalValue))
                                        {
                                            statementOfDistributionToBeneficiary.DISTBENTRT7 = currentDecimalValue;
                                        }
                                    }
                                }
                                _found = true;
                            }
                    
                            _currentXPath.Pop();
                            #endregion IncomeTaxPayAsYouGoWithholdingCreditForAmountsWithheldFromForeignResidentsA
                    
                            #region IncomeTaxFrankingCreditsReceivedFromNewZealandCompaniesA
                            _currentXPath.Push("/tns:IncomeTaxFrankingCreditsReceivedFromNewZealandCompaniesA");
                            //6. use case
                            if (ReadToNextElement(reader,false) && reader.LocalName == "IncomeTaxFrankingCreditsReceivedFromNewZealandCompaniesA")
                            {
                                if (!IsEmptyOrNilElement(reader))
                                {
                                    ReadNext(reader);
                                    if (reader.NodeType == XmlNodeType.Text || reader.NodeType == XmlNodeType.CDATA)
                                    {
                                        currentValue = reader.Value;
                                        ReadNext(reader); // consume the end element so we detect any validation errors before _currentXPath is updated.
                                        if (Decimal.TryParse(currentValue, out currentDecimalValue))
                                        {
                                            statementOfDistributionToBeneficiary.DISTBENTRT8 = currentDecimalValue;
                                        }
                                    }
                                }
                                _found = true;
                            }
                    
                            _currentXPath.Pop();
                            #endregion IncomeTaxFrankingCreditsReceivedFromNewZealandCompaniesA
                    
                            #region IncomeTaxPayAsYouGoWithholdingCreditForTaxWithheldWhereABNNotQuotedA
                            _currentXPath.Push("/tns:IncomeTaxPayAsYouGoWithholdingCreditForTaxWithheldWhereABNNotQuotedA");
                            //6. use case
                            if (ReadToNextElement(reader,false) && reader.LocalName == "IncomeTaxPayAsYouGoWithholdingCreditForTaxWithheldWhereABNNotQuotedA")
                            {
                                if (!IsEmptyOrNilElement(reader))
                                {
                                    ReadNext(reader);
                                    if (reader.NodeType == XmlNodeType.Text || reader.NodeType == XmlNodeType.CDATA)
                                    {
                                        currentValue = reader.Value;
                                        ReadNext(reader); // consume the end element so we detect any validation errors before _currentXPath is updated.
                                        if (Decimal.TryParse(currentValue, out currentDecimalValue))
                                        {
                                            statementOfDistributionToBeneficiary.DISTBENTRT9 = currentDecimalValue;
                                        }
                                    }
                                }
                                _found = true;
                            }
                    
                            _currentXPath.Pop();
                            #endregion IncomeTaxPayAsYouGoWithholdingCreditForTaxWithheldWhereABNNotQuotedA
                    
                            #region IncomeTaxableMinorBeneficiaryA
                            _currentXPath.Push("/tns:IncomeTaxableMinorBeneficiaryA");
                            //6. use case
                            if (ReadToNextElement(reader,false) && reader.LocalName == "IncomeTaxableMinorBeneficiaryA")
                            {
                                if (!IsEmptyOrNilElement(reader))
                                {
                                    ReadNext(reader);
                                    if (reader.NodeType == XmlNodeType.Text || reader.NodeType == XmlNodeType.CDATA)
                                    {
                                        currentValue = reader.Value;
                                        ReadNext(reader); // consume the end element so we detect any validation errors before _currentXPath is updated.
                                        if (Decimal.TryParse(currentValue, out currentDecimalValue))
                                        {
                                            statementOfDistributionToBeneficiary.DISTBENTRT10 = currentDecimalValue;
                                        }
                                    }
                                }
                                _found = true;
                            }
                    
                            _currentXPath.Pop();
                            #endregion IncomeTaxableMinorBeneficiaryA
                    
                            #region IncomeDistributionFrankedA
                            _currentXPath.Push("/tns:IncomeDistributionFrankedA");
                            //6. use case
                            if (ReadToNextElement(reader,false) && reader.LocalName == "IncomeDistributionFrankedA")
                            {
                                if (!IsEmptyOrNilElement(reader))
                                {
                                    ReadNext(reader);
                                    if (reader.NodeType == XmlNodeType.Text || reader.NodeType == XmlNodeType.CDATA)
                                    {
                                        currentValue = reader.Value;
                                        ReadNext(reader); // consume the end element so we detect any validation errors before _currentXPath is updated.
                                        if (Decimal.TryParse(currentValue, out currentDecimalValue))
                                        {
                                            statementOfDistributionToBeneficiary.DISTBENTRT11 = currentDecimalValue;
                                        }
                                    }
                                }
                                _found = true;
                            }
                    
                            _currentXPath.Pop();
                            #endregion IncomeDistributionFrankedA
                    
                            #region IncomeTaxFrankingCreditsReceivedFromAustralianCompaniesA
                            _currentXPath.Push("/tns:IncomeTaxFrankingCreditsReceivedFromAustralianCompaniesA");
                            //6. use case
                            if (ReadToNextElement(reader,false) && reader.LocalName == "IncomeTaxFrankingCreditsReceivedFromAustralianCompaniesA")
                            {
                                if (!IsEmptyOrNilElement(reader))
                                {
                                    ReadNext(reader);
                                    if (reader.NodeType == XmlNodeType.Text || reader.NodeType == XmlNodeType.CDATA)
                                    {
                                        currentValue = reader.Value;
                                        ReadNext(reader); // consume the end element so we detect any validation errors before _currentXPath is updated.
                                        if (Decimal.TryParse(currentValue, out currentDecimalValue))
                                        {
                                            statementOfDistributionToBeneficiary.DISTBENTRT12 = currentDecimalValue;
                                        }
                                    }
                                }
                                _found = true;
                            }
                    
                            _currentXPath.Pop();
                            #endregion IncomeTaxFrankingCreditsReceivedFromAustralianCompaniesA
                    
                            #region IncomeTaxPayAsYouGoWithholdingCreditForAmountsWithheldWhereTFNNotQuotedA
                            _currentXPath.Push("/tns:IncomeTaxPayAsYouGoWithholdingCreditForAmountsWithheldWhereTFNNotQuotedA");
                            //6. use case
                            if (ReadToNextElement(reader,false) && reader.LocalName == "IncomeTaxPayAsYouGoWithholdingCreditForAmountsWithheldWhereTFNNotQuotedA")
                            {
                                if (!IsEmptyOrNilElement(reader))
                                {
                                    ReadNext(reader);
                                    if (reader.NodeType == XmlNodeType.Text || reader.NodeType == XmlNodeType.CDATA)
                                    {
                                        currentValue = reader.Value;
                                        ReadNext(reader); // consume the end element so we detect any validation errors before _currentXPath is updated.
                                        if (Decimal.TryParse(currentValue, out currentDecimalValue))
                                        {
                                            statementOfDistributionToBeneficiary.DISTBENTRT13 = currentDecimalValue;
                                        }
                                    }
                                }
                                _found = true;
                            }
                    
                            _currentXPath.Pop();
                            #endregion IncomeTaxPayAsYouGoWithholdingCreditForAmountsWithheldWhereTFNNotQuotedA
                    
                            #region IncomeTaxPayAsYouGoWithholdingCreditForTaxWithheldFromCloselyHeldTrustA
                            _currentXPath.Push("/tns:IncomeTaxPayAsYouGoWithholdingCreditForTaxWithheldFromCloselyHeldTrustA");
                            //6. use case
                            if (ReadToNextElement(reader,false) && reader.LocalName == "IncomeTaxPayAsYouGoWithholdingCreditForTaxWithheldFromCloselyHeldTrustA")
                            {
                                if (!IsEmptyOrNilElement(reader))
                                {
                                    ReadNext(reader);
                                    if (reader.NodeType == XmlNodeType.Text || reader.NodeType == XmlNodeType.CDATA)
                                    {
                                        currentValue = reader.Value;
                                        ReadNext(reader); // consume the end element so we detect any validation errors before _currentXPath is updated.
                                        if (Decimal.TryParse(currentValue, out currentDecimalValue))
                                        {
                                            statementOfDistributionToBeneficiary.DISTBENTRT14 = currentDecimalValue;
                                        }
                                    }
                                }
                                _found = true;
                            }
                    
                            _currentXPath.Pop();
                            #endregion IncomeTaxPayAsYouGoWithholdingCreditForTaxWithheldFromCloselyHeldTrustA
                    
                            #region IncomeCapitalGainsNetA
                            _currentXPath.Push("/tns:IncomeCapitalGainsNetA");
                            //6. use case
                            if (ReadToNextElement(reader,false) && reader.LocalName == "IncomeCapitalGainsNetA")
                            {
                                if (!IsEmptyOrNilElement(reader))
                                {
                                    ReadNext(reader);
                                    if (reader.NodeType == XmlNodeType.Text || reader.NodeType == XmlNodeType.CDATA)
                                    {
                                        currentValue = reader.Value;
                                        ReadNext(reader); // consume the end element so we detect any validation errors before _currentXPath is updated.
                                        if (Decimal.TryParse(currentValue, out currentDecimalValue))
                                        {
                                            statementOfDistributionToBeneficiary.DISTBENTRT15 = currentDecimalValue;
                                        }
                                    }
                                }
                                _found = true;
                            }
                    
                            _currentXPath.Pop();
                            #endregion IncomeCapitalGainsNetA
                    
                            #region CapitalGainsTotalA
                            _currentXPath.Push("/tns:CapitalGainsTotalA");
                            //6. use case
                            if (ReadToNextElement(reader,false) && reader.LocalName == "CapitalGainsTotalA")
                            {
                                if (!IsEmptyOrNilElement(reader))
                                {
                                    ReadNext(reader);
                                    if (reader.NodeType == XmlNodeType.Text || reader.NodeType == XmlNodeType.CDATA)
                                    {
                                        currentValue = reader.Value;
                                        ReadNext(reader); // consume the end element so we detect any validation errors before _currentXPath is updated.
                                        if (Decimal.TryParse(currentValue, out currentDecimalValue))
                                        {
                                            statementOfDistributionToBeneficiary.DISTBENTRT16 = currentDecimalValue;
                                        }
                                    }
                                }
                                _found = true;
                            }
                    
                            _currentXPath.Pop();
                            #endregion CapitalGainsTotalA
                    
                            #region CapitalLossesTotalA
                            _currentXPath.Push("/tns:CapitalLossesTotalA");
                            //6. use case
                            if (ReadToNextElement(reader,false) && reader.LocalName == "CapitalLossesTotalA")
                            {
                                if (!IsEmptyOrNilElement(reader))
                                {
                                    ReadNext(reader);
                                    if (reader.NodeType == XmlNodeType.Text || reader.NodeType == XmlNodeType.CDATA)
                                    {
                                        currentValue = reader.Value;
                                        ReadNext(reader); // consume the end element so we detect any validation errors before _currentXPath is updated.
                                        if (Decimal.TryParse(currentValue, out currentDecimalValue))
                                        {
                                            statementOfDistributionToBeneficiary.DISTBENTRT17 = currentDecimalValue;
                                        }
                                    }
                                }
                                _found = true;
                            }
                    
                            _currentXPath.Pop();
                            #endregion CapitalLossesTotalA
                    
                            #region TaxConcessionCapitalGainsDiscountTotalA
                            _currentXPath.Push("/tns:TaxConcessionCapitalGainsDiscountTotalA");
                            //6. use case
                            if (ReadToNextElement(reader,false) && reader.LocalName == "TaxConcessionCapitalGainsDiscountTotalA")
                            {
                                if (!IsEmptyOrNilElement(reader))
                                {
                                    ReadNext(reader);
                                    if (reader.NodeType == XmlNodeType.Text || reader.NodeType == XmlNodeType.CDATA)
                                    {
                                        currentValue = reader.Value;
                                        ReadNext(reader); // consume the end element so we detect any validation errors before _currentXPath is updated.
                                        if (Decimal.TryParse(currentValue, out currentDecimalValue))
                                        {
                                            statementOfDistributionToBeneficiary.DISTBENTRT18 = currentDecimalValue;
                                        }
                                    }
                                }
                                _found = true;
                            }
                    
                            _currentXPath.Pop();
                            #endregion TaxConcessionCapitalGainsDiscountTotalA
                    
                            #region TaxConcessionCapitalGainsDiscountAndSmallBusinessConcessionsTotalA
                            _currentXPath.Push("/tns:TaxConcessionCapitalGainsDiscountAndSmallBusinessConcessionsTotalA");
                            //6. use case
                            if (ReadToNextElement(reader,false) && reader.LocalName == "TaxConcessionCapitalGainsDiscountAndSmallBusinessConcessionsTotalA")
                            {
                                if (!IsEmptyOrNilElement(reader))
                                {
                                    ReadNext(reader);
                                    if (reader.NodeType == XmlNodeType.Text || reader.NodeType == XmlNodeType.CDATA)
                                    {
                                        currentValue = reader.Value;
                                        ReadNext(reader); // consume the end element so we detect any validation errors before _currentXPath is updated.
                                        if (Decimal.TryParse(currentValue, out currentDecimalValue))
                                        {
                                            statementOfDistributionToBeneficiary.DISTBENTRT19 = currentDecimalValue;
                                        }
                                    }
                                }
                                _found = true;
                            }
                    
                            _currentXPath.Pop();
                            #endregion TaxConcessionCapitalGainsDiscountAndSmallBusinessConcessionsTotalA
                    
                            #region CapitalGainsNonConcessionalManagedInvestmentTrustIncomeA
                            _currentXPath.Push("/tns:CapitalGainsNonConcessionalManagedInvestmentTrustIncomeA");
                            //6. use case
                            if (ReadToNextElement(reader,false) && reader.LocalName == "CapitalGainsNonConcessionalManagedInvestmentTrustIncomeA")
                            {
                                if (!IsEmptyOrNilElement(reader))
                                {
                                    ReadNext(reader);
                                    if (reader.NodeType == XmlNodeType.Text || reader.NodeType == XmlNodeType.CDATA)
                                    {
                                        currentValue = reader.Value;
                                        ReadNext(reader); // consume the end element so we detect any validation errors before _currentXPath is updated.
                                        if (Decimal.TryParse(currentValue, out currentDecimalValue))
                                        {
                                            statementOfDistributionToBeneficiary.DISTBENTRT20 = currentDecimalValue;
                                        }
                                    }
                                }
                                _found = true;
                            }
                    
                            _currentXPath.Pop();
                            #endregion CapitalGainsNonConcessionalManagedInvestmentTrustIncomeA
                    
                            #region CapitalGainsExcludedFromNonConcessionalManagedInvestmentTrustIncomeA
                            _currentXPath.Push("/tns:CapitalGainsExcludedFromNonConcessionalManagedInvestmentTrustIncomeA");
                            //6. use case
                            if (ReadToNextElement(reader,false) && reader.LocalName == "CapitalGainsExcludedFromNonConcessionalManagedInvestmentTrustIncomeA")
                            {
                                if (!IsEmptyOrNilElement(reader))
                                {
                                    ReadNext(reader);
                                    if (reader.NodeType == XmlNodeType.Text || reader.NodeType == XmlNodeType.CDATA)
                                    {
                                        currentValue = reader.Value;
                                        ReadNext(reader); // consume the end element so we detect any validation errors before _currentXPath is updated.
                                        if (Decimal.TryParse(currentValue, out currentDecimalValue))
                                        {
                                            statementOfDistributionToBeneficiary.DISTBENTRT21 = currentDecimalValue;
                                        }
                                    }
                                }
                                _found = true;
                            }
                    
                            _currentXPath.Pop();
                            #endregion CapitalGainsExcludedFromNonConcessionalManagedInvestmentTrustIncomeA
                    
                            #region IncomeTaxPayAsYouGoWithholdingCreditForCapitalGainsWithheldFromForeignResidentsA
                            _currentXPath.Push("/tns:IncomeTaxPayAsYouGoWithholdingCreditForCapitalGainsWithheldFromForeignResidentsA");
                            //6. use case
                            if (ReadToNextElement(reader,false) && reader.LocalName == "IncomeTaxPayAsYouGoWithholdingCreditForCapitalGainsWithheldFromForeignResidentsA")
                            {
                                if (!IsEmptyOrNilElement(reader))
                                {
                                    ReadNext(reader);
                                    if (reader.NodeType == XmlNodeType.Text || reader.NodeType == XmlNodeType.CDATA)
                                    {
                                        currentValue = reader.Value;
                                        ReadNext(reader); // consume the end element so we detect any validation errors before _currentXPath is updated.
                                        if (Decimal.TryParse(currentValue, out currentDecimalValue))
                                        {
                                            statementOfDistributionToBeneficiary.DISTBENTRT22 = currentDecimalValue;
                                        }
                                    }
                                }
                                _found = true;
                            }
                    
                            _currentXPath.Pop();
                            #endregion IncomeTaxPayAsYouGoWithholdingCreditForCapitalGainsWithheldFromForeignResidentsA
                    
                            #region IncomeTaxAttributedForeignIncomeA
                            _currentXPath.Push("/tns:IncomeTaxAttributedForeignIncomeA");
                            //6. use case
                            if (ReadToNextElement(reader,false) && reader.LocalName == "IncomeTaxAttributedForeignIncomeA")
                            {
                                if (!IsEmptyOrNilElement(reader))
                                {
                                    ReadNext(reader);
                                    if (reader.NodeType == XmlNodeType.Text || reader.NodeType == XmlNodeType.CDATA)
                                    {
                                        currentValue = reader.Value;
                                        ReadNext(reader); // consume the end element so we detect any validation errors before _currentXPath is updated.
                                        if (Decimal.TryParse(currentValue, out currentDecimalValue))
                                        {
                                            statementOfDistributionToBeneficiary.DISTBENTRT23 = currentDecimalValue;
                                        }
                                    }
                                }
                                _found = true;
                            }
                    
                            _currentXPath.Pop();
                            #endregion IncomeTaxAttributedForeignIncomeA
                    
                            #region IncomeInternationalDealingsNetA
                            _currentXPath.Push("/tns:IncomeInternationalDealingsNetA");
                            //6. use case
                            if (ReadToNextElement(reader,false) && reader.LocalName == "IncomeInternationalDealingsNetA")
                            {
                                if (!IsEmptyOrNilElement(reader))
                                {
                                    ReadNext(reader);
                                    if (reader.NodeType == XmlNodeType.Text || reader.NodeType == XmlNodeType.CDATA)
                                    {
                                        currentValue = reader.Value;
                                        ReadNext(reader); // consume the end element so we detect any validation errors before _currentXPath is updated.
                                        if (Decimal.TryParse(currentValue, out currentDecimalValue))
                                        {
                                            statementOfDistributionToBeneficiary.DISTBENTRT24 = currentDecimalValue;
                                        }
                                    }
                                }
                                _found = true;
                            }
                    
                            _currentXPath.Pop();
                            #endregion IncomeInternationalDealingsNetA
                    
                            #region IncomeInternationalDealingsTaxOffsetA
                            _currentXPath.Push("/tns:IncomeInternationalDealingsTaxOffsetA");
                            //6. use case
                            if (ReadToNextElement(reader,false) && reader.LocalName == "IncomeInternationalDealingsTaxOffsetA")
                            {
                                if (!IsEmptyOrNilElement(reader))
                                {
                                    ReadNext(reader);
                                    if (reader.NodeType == XmlNodeType.Text || reader.NodeType == XmlNodeType.CDATA)
                                    {
                                        currentValue = reader.Value;
                                        ReadNext(reader); // consume the end element so we detect any validation errors before _currentXPath is updated.
                                        if (Decimal.TryParse(currentValue, out currentDecimalValue))
                                        {
                                            statementOfDistributionToBeneficiary.DISTBENTRT25 = currentDecimalValue;
                                        }
                                    }
                                }
                                _found = true;
                            }
                    
                            _currentXPath.Pop();
                            #endregion IncomeInternationalDealingsTaxOffsetA
                    
                            #region TaxOffsetClaimNationalRentalAffordabilitySchemeEntitlementA
                            _currentXPath.Push("/tns:TaxOffsetClaimNationalRentalAffordabilitySchemeEntitlementA");
                            //6. use case
                            if (ReadToNextElement(reader,false) && reader.LocalName == "TaxOffsetClaimNationalRentalAffordabilitySchemeEntitlementA")
                            {
                                if (!IsEmptyOrNilElement(reader))
                                {
                                    ReadNext(reader);
                                    if (reader.NodeType == XmlNodeType.Text || reader.NodeType == XmlNodeType.CDATA)
                                    {
                                        currentValue = reader.Value;
                                        ReadNext(reader); // consume the end element so we detect any validation errors before _currentXPath is updated.
                                        if (Decimal.TryParse(currentValue, out currentDecimalValue))
                                        {
                                            statementOfDistributionToBeneficiary.DISTBENTRT26 = currentDecimalValue;
                                        }
                                    }
                                }
                                _found = true;
                            }
                    
                            _currentXPath.Pop();
                            #endregion TaxOffsetClaimNationalRentalAffordabilitySchemeEntitlementA
                    
                            #region IncomeTaxExplorationCreditsDistributedA
                            _currentXPath.Push("/tns:IncomeTaxExplorationCreditsDistributedA");
                            //6. use case
                            if (ReadToNextElement(reader,false) && reader.LocalName == "IncomeTaxExplorationCreditsDistributedA")
                            {
                                if (!IsEmptyOrNilElement(reader))
                                {
                                    ReadNext(reader);
                                    if (reader.NodeType == XmlNodeType.Text || reader.NodeType == XmlNodeType.CDATA)
                                    {
                                        currentValue = reader.Value;
                                        ReadNext(reader); // consume the end element so we detect any validation errors before _currentXPath is updated.
                                        if (Decimal.TryParse(currentValue, out currentDecimalValue))
                                        {
                                            statementOfDistributionToBeneficiary.DISTBENTRT27 = currentDecimalValue;
                                        }
                                    }
                                }
                                _found = true;
                            }
                    
                            _currentXPath.Pop();
                            #endregion IncomeTaxExplorationCreditsDistributedA
                    
                            #region IncomeSmallBusinessEntityNetA
                            _currentXPath.Push("/tns:IncomeSmallBusinessEntityNetA");
                            //6. use case
                            if (ReadToNextElement(reader,false) && reader.LocalName == "IncomeSmallBusinessEntityNetA")
                            {
                                if (!IsEmptyOrNilElement(reader))
                                {
                                    ReadNext(reader);
                                    if (reader.NodeType == XmlNodeType.Text || reader.NodeType == XmlNodeType.CDATA)
                                    {
                                        currentValue = reader.Value;
                                        ReadNext(reader); // consume the end element so we detect any validation errors before _currentXPath is updated.
                                        if (Decimal.TryParse(currentValue, out currentDecimalValue))
                                        {
                                            statementOfDistributionToBeneficiary.DISTBENTRT28 = currentDecimalValue;
                                        }
                                    }
                                }
                                _found = true;
                            }
                    
                            _currentXPath.Pop();
                            #endregion IncomeSmallBusinessEntityNetA
                    
                            #region ShareOfIncomePrimaryProduction
                            _currentXPath.Push("/tns:ShareOfIncomePrimaryProduction");
                            //3. use case
                            if (ReadToNextElement(reader,false) && reader.LocalName == "ShareOfIncomePrimaryProduction")
                            {
                                statementOfDistributionToBeneficiary.RP_StatementOfDistributionToBeneficiary_Information_ShareOfIncomePrimaryProductionCollectionExists = true;
                                statementOfDistributionToBeneficiary.RP_StatementOfDistributionToBeneficiary_Information_ShareOfIncomePrimaryProductionCollectionCount += 1;
                                _found = true; 
                        
                                #region BeneficiaryShareA
                                _currentXPath.Push("/tns:BeneficiaryShareA");
                                //6. use case
                                if (ReadToNextElement(reader,false) && reader.LocalName == "BeneficiaryShareA")
                                {
                                    if (!IsEmptyOrNilElement(reader))
                                    {
                                        ReadNext(reader);
                                        if (reader.NodeType == XmlNodeType.Text || reader.NodeType == XmlNodeType.CDATA)
                                        {
                                            currentValue = reader.Value;
                                            ReadNext(reader); // consume the end element so we detect any validation errors before _currentXPath is updated.
                                            if (Decimal.TryParse(currentValue, out currentDecimalValue))
                                            {
                                                statementOfDistributionToBeneficiary.DISTBENTRT29 = currentDecimalValue;
                                            }
                                        }
                                    }
                                    _found = true;
                                }
                        
                                _currentXPath.Pop();
                                #endregion BeneficiaryShareA
                        
                                #region NonConcessionalManagedInvestmentTrustA
                                _currentXPath.Push("/tns:NonConcessionalManagedInvestmentTrustA");
                                //6. use case
                                if (ReadToNextElement(reader,false) && reader.LocalName == "NonConcessionalManagedInvestmentTrustA")
                                {
                                    if (!IsEmptyOrNilElement(reader))
                                    {
                                        ReadNext(reader);
                                        if (reader.NodeType == XmlNodeType.Text || reader.NodeType == XmlNodeType.CDATA)
                                        {
                                            currentValue = reader.Value;
                                            ReadNext(reader); // consume the end element so we detect any validation errors before _currentXPath is updated.
                                            if (Decimal.TryParse(currentValue, out currentDecimalValue))
                                            {
                                                statementOfDistributionToBeneficiary.DISTBENTRT30 = currentDecimalValue;
                                            }
                                        }
                                    }
                                    _found = true;
                                }
                        
                                _currentXPath.Pop();
                                #endregion NonConcessionalManagedInvestmentTrustA
                        
                                #region ExcludedFromNonConcessionalManagedInvestmentTrustA
                                _currentXPath.Push("/tns:ExcludedFromNonConcessionalManagedInvestmentTrustA");
                                //6. use case
                                if (ReadToNextElement(reader,false) && reader.LocalName == "ExcludedFromNonConcessionalManagedInvestmentTrustA")
                                {
                                    if (!IsEmptyOrNilElement(reader))
                                    {
                                        ReadNext(reader);
                                        if (reader.NodeType == XmlNodeType.Text || reader.NodeType == XmlNodeType.CDATA)
                                        {
                                            currentValue = reader.Value;
                                            ReadNext(reader); // consume the end element so we detect any validation errors before _currentXPath is updated.
                                            if (Decimal.TryParse(currentValue, out currentDecimalValue))
                                            {
                                                statementOfDistributionToBeneficiary.DISTBENTRT31 = currentDecimalValue;
                                            }
                                        }
                                    }
                                    _found = true;
                                }
                        
                                _currentXPath.Pop();
                                #endregion ExcludedFromNonConcessionalManagedInvestmentTrustA
                            } // End of if ShareOfIncomePrimaryProduction node exists
                    
                            _currentXPath.Pop();
                            #endregion ShareOfIncomePrimaryProduction
                    
                            #region ShareOfIncomeNonPrimaryProduction
                            _currentXPath.Push("/tns:ShareOfIncomeNonPrimaryProduction");
                            //3. use case
                            if (ReadToNextElement(reader,false) && reader.LocalName == "ShareOfIncomeNonPrimaryProduction")
                            {
                                statementOfDistributionToBeneficiary.RP_StatementOfDistributionToBeneficiary_Information_ShareOfIncomeNonPrimaryProductionCollectionExists = true;
                                statementOfDistributionToBeneficiary.RP_StatementOfDistributionToBeneficiary_Information_ShareOfIncomeNonPrimaryProductionCollectionCount += 1;
                                _found = true; 
                        
                                #region BeneficiaryShareA
                                _currentXPath.Push("/tns:BeneficiaryShareA");
                                //6. use case
                                if (ReadToNextElement(reader,false) && reader.LocalName == "BeneficiaryShareA")
                                {
                                    if (!IsEmptyOrNilElement(reader))
                                    {
                                        ReadNext(reader);
                                        if (reader.NodeType == XmlNodeType.Text || reader.NodeType == XmlNodeType.CDATA)
                                        {
                                            currentValue = reader.Value;
                                            ReadNext(reader); // consume the end element so we detect any validation errors before _currentXPath is updated.
                                            if (Decimal.TryParse(currentValue, out currentDecimalValue))
                                            {
                                                statementOfDistributionToBeneficiary.DISTBENTRT32 = currentDecimalValue;
                                            }
                                        }
                                    }
                                    _found = true;
                                }
                        
                                _currentXPath.Pop();
                                #endregion BeneficiaryShareA
                        
                                #region NonConcessionalManagedInvestmentTrustA
                                _currentXPath.Push("/tns:NonConcessionalManagedInvestmentTrustA");
                                //6. use case
                                if (ReadToNextElement(reader,false) && reader.LocalName == "NonConcessionalManagedInvestmentTrustA")
                                {
                                    if (!IsEmptyOrNilElement(reader))
                                    {
                                        ReadNext(reader);
                                        if (reader.NodeType == XmlNodeType.Text || reader.NodeType == XmlNodeType.CDATA)
                                        {
                                            currentValue = reader.Value;
                                            ReadNext(reader); // consume the end element so we detect any validation errors before _currentXPath is updated.
                                            if (Decimal.TryParse(currentValue, out currentDecimalValue))
                                            {
                                                statementOfDistributionToBeneficiary.DISTBENTRT33 = currentDecimalValue;
                                            }
                                        }
                                    }
                                    _found = true;
                                }
                        
                                _currentXPath.Pop();
                                #endregion NonConcessionalManagedInvestmentTrustA
                        
                                #region ExcludedFromNonConcessionalManagedInvestmentTrustA
                                _currentXPath.Push("/tns:ExcludedFromNonConcessionalManagedInvestmentTrustA");
                                //6. use case
                                if (ReadToNextElement(reader,false) && reader.LocalName == "ExcludedFromNonConcessionalManagedInvestmentTrustA")
                                {
                                    if (!IsEmptyOrNilElement(reader))
                                    {
                                        ReadNext(reader);
                                        if (reader.NodeType == XmlNodeType.Text || reader.NodeType == XmlNodeType.CDATA)
                                        {
                                            currentValue = reader.Value;
                                            ReadNext(reader); // consume the end element so we detect any validation errors before _currentXPath is updated.
                                            if (Decimal.TryParse(currentValue, out currentDecimalValue))
                                            {
                                                statementOfDistributionToBeneficiary.DISTBENTRT34 = currentDecimalValue;
                                            }
                                        }
                                    }
                                    _found = true;
                                }
                        
                                _currentXPath.Pop();
                                #endregion ExcludedFromNonConcessionalManagedInvestmentTrustA
                            } // End of if ShareOfIncomeNonPrimaryProduction node exists
                    
                            _currentXPath.Pop();
                            #endregion ShareOfIncomeNonPrimaryProduction
                    
                            #region EarlyStageVentureTaxOffsetTaxOffsetClaimNonRefundableOtherA
                            _currentXPath.Push("/tns:EarlyStageVentureTaxOffsetTaxOffsetClaimNonRefundableOtherA");
                            //6. use case
                            if (ReadToNextElement(reader,false) && reader.LocalName == "EarlyStageVentureTaxOffsetTaxOffsetClaimNonRefundableOtherA")
                            {
                                if (!IsEmptyOrNilElement(reader))
                                {
                                    ReadNext(reader);
                                    if (reader.NodeType == XmlNodeType.Text || reader.NodeType == XmlNodeType.CDATA)
                                    {
                                        currentValue = reader.Value;
                                        ReadNext(reader); // consume the end element so we detect any validation errors before _currentXPath is updated.
                                        if (Decimal.TryParse(currentValue, out currentDecimalValue))
                                        {
                                            statementOfDistributionToBeneficiary.DISTBENTRT35 = currentDecimalValue;
                                        }
                                        statementOfDistributionToBeneficiary.RP_StatementOfDistributionToBeneficiary_Information_EarlyStageVentureTaxOffsetCollectionExists = true;
                                        statementOfDistributionToBeneficiary.RP_StatementOfDistributionToBeneficiary_Information_EarlyStageVentureTaxOffsetCollectionCount += 1;
                                    }
                                }
                                _found = true;
                            }
                    
                            _currentXPath.Pop();
                            #endregion EarlyStageVentureTaxOffsetTaxOffsetClaimNonRefundableOtherA
                    
                            #region EarlyStageInvestorTaxOffsetTaxOffsetClaimNonRefundableOtherA
                            _currentXPath.Push("/tns:EarlyStageInvestorTaxOffsetTaxOffsetClaimNonRefundableOtherA");
                            //6. use case
                            if (ReadToNextElement(reader,false) && reader.LocalName == "EarlyStageInvestorTaxOffsetTaxOffsetClaimNonRefundableOtherA")
                            {
                                if (!IsEmptyOrNilElement(reader))
                                {
                                    ReadNext(reader);
                                    if (reader.NodeType == XmlNodeType.Text || reader.NodeType == XmlNodeType.CDATA)
                                    {
                                        currentValue = reader.Value;
                                        ReadNext(reader); // consume the end element so we detect any validation errors before _currentXPath is updated.
                                        if (Decimal.TryParse(currentValue, out currentDecimalValue))
                                        {
                                            statementOfDistributionToBeneficiary.DISTBENTRT36 = currentDecimalValue;
                                        }
                                        statementOfDistributionToBeneficiary.RP_StatementOfDistributionToBeneficiary_Information_EarlyStageInvestorTaxOffsetCollectionExists = true;
                                        statementOfDistributionToBeneficiary.RP_StatementOfDistributionToBeneficiary_Information_EarlyStageInvestorTaxOffsetCollectionCount += 1;
                                    }
                                }
                                _found = true;
                            }
                    
                            _currentXPath.Pop();
                            #endregion EarlyStageInvestorTaxOffsetTaxOffsetClaimNonRefundableOtherA
                    
                            #region NonResidentAdditionalInformation
                            _currentXPath.Push("/tns:NonResidentAdditionalInformation");
                            //3. use case
                            if (ReadToNextElement(reader,false) && reader.LocalName == "NonResidentAdditionalInformation")
                            {
                                statementOfDistributionToBeneficiary.RP_StatementOfDistributionToBeneficiary_Information_NonResidentAdditionalInformationCollectionExists = true;
                                statementOfDistributionToBeneficiary.RP_StatementOfDistributionToBeneficiary_Information_NonResidentAdditionalInformationCollectionCount += 1;
                                _found = true; 
                        
                                #region InternationalDealingsAssessableIncomeNonResidentBeneficiaryNonTrusteeA
                                _currentXPath.Push("/tns:InternationalDealingsAssessableIncomeNonResidentBeneficiaryNonTrusteeA");
                                //6. use case
                                if (ReadToNextElement(reader,false) && reader.LocalName == "InternationalDealingsAssessableIncomeNonResidentBeneficiaryNonTrusteeA")
                                {
                                    if (!IsEmptyOrNilElement(reader))
                                    {
                                        ReadNext(reader);
                                        if (reader.NodeType == XmlNodeType.Text || reader.NodeType == XmlNodeType.CDATA)
                                        {
                                            currentValue = reader.Value;
                                            ReadNext(reader); // consume the end element so we detect any validation errors before _currentXPath is updated.
                                            if (Decimal.TryParse(currentValue, out currentDecimalValue))
                                            {
                                                statementOfDistributionToBeneficiary.DISTBENTRT37 = currentDecimalValue;
                                            }
                                        }
                                    }
                                    _found = true;
                                }
                        
                                _currentXPath.Pop();
                                #endregion InternationalDealingsAssessableIncomeNonResidentBeneficiaryNonTrusteeA
                        
                                #region InternationalDealingsAssessableIncomeNonResidentBeneficiaryTrusteeA
                                _currentXPath.Push("/tns:InternationalDealingsAssessableIncomeNonResidentBeneficiaryTrusteeA");
                                //6. use case
                                if (ReadToNextElement(reader,false) && reader.LocalName == "InternationalDealingsAssessableIncomeNonResidentBeneficiaryTrusteeA")
                                {
                                    if (!IsEmptyOrNilElement(reader))
                                    {
                                        ReadNext(reader);
                                        if (reader.NodeType == XmlNodeType.Text || reader.NodeType == XmlNodeType.CDATA)
                                        {
                                            currentValue = reader.Value;
                                            ReadNext(reader); // consume the end element so we detect any validation errors before _currentXPath is updated.
                                            if (Decimal.TryParse(currentValue, out currentDecimalValue))
                                            {
                                                statementOfDistributionToBeneficiary.DISTBENTRT38 = currentDecimalValue;
                                            }
                                        }
                                    }
                                    _found = true;
                                }
                        
                                _currentXPath.Pop();
                                #endregion InternationalDealingsAssessableIncomeNonResidentBeneficiaryTrusteeA
                            } // End of if NonResidentAdditionalInformation node exists
                    
                            _currentXPath.Pop();
                            #endregion NonResidentAdditionalInformation
                        } // End of if Information node exists
                
                        _currentXPath.Pop();
                        #endregion Information
                
                        #region AnnualTrusteePaymentReportInformationIncomeTaxPayAsYouGoWithholdingCreditForTaxWithheldFromCloselyHeldTrustA
                        _currentXPath.Push("/tns:AnnualTrusteePaymentReportInformationIncomeTaxPayAsYouGoWithholdingCreditForTaxWithheldFromCloselyHeldTrustA");
                        //6. use case
                        if (ReadToNextElement(reader,false) && reader.LocalName == "AnnualTrusteePaymentReportInformationIncomeTaxPayAsYouGoWithholdingCreditForTaxWithheldFromCloselyHeldTrustA")
                        {
                            if (!IsEmptyOrNilElement(reader))
                            {
                                ReadNext(reader);
                                if (reader.NodeType == XmlNodeType.Text || reader.NodeType == XmlNodeType.CDATA)
                                {
                                    currentValue = reader.Value;
                                    ReadNext(reader); // consume the end element so we detect any validation errors before _currentXPath is updated.
                                    if (Decimal.TryParse(currentValue, out currentDecimalValue))
                                    {
                                        statementOfDistributionToBeneficiary.DISTBENTRT39 = currentDecimalValue;
                                    }
                                    statementOfDistributionToBeneficiary.RP_StatementOfDistributionToBeneficiary_AnnualTrusteePaymentReportInformationCollectionExists = true;
                                    statementOfDistributionToBeneficiary.RP_StatementOfDistributionToBeneficiary_AnnualTrusteePaymentReportInformationCollectionCount += 1;
                                }
                            }
                            _found = true;
                        }
                
                        _currentXPath.Pop();
                        #endregion AnnualTrusteePaymentReportInformationIncomeTaxPayAsYouGoWithholdingCreditForTaxWithheldFromCloselyHeldTrustA
                    _currentXPath.Pop();
                    } // End of while loop for StatementOfDistributionToBeneficiary
                } // End of if StatementOfDistributionToBeneficiaryCollection node exists
        
                _currentXPath.Pop();
                #endregion StatementOfDistributionToBeneficiary
            } // End of if RP node exists
    
            _currentXPath.Pop();
            #endregion RP

            while (reader.EOF != true)
                reader.Read();

            return report;
        }

        private string _elementCsvList = "RP#PeriodStartD,RP#PeriodEndD,RP#TaxFileNumberId,StatementOfDistributionToBeneficiary#AustralianBusinessNumberId,StatementOfDistributionToBeneficiary#AustralianCompanyNumberId,StatementOfDistributionToBeneficiary#MiscellaneousInvestorReferenceNumberId,StatementOfDistributionToBeneficiary#OrganisationNameDetailsOrganisationalNameT,DistributingTrust,StatementOfDistributionToBeneficiary#IncomeTrustEstateIncomeShareA,StatementOfDistributionToBeneficiary#IncomeTaxPayAsYouGoWithholdingCreditForAmountsWithheldFromForeignResidentsA,StatementOfDistributionToBeneficiary#IncomeTaxFrankingCreditsReceivedFromNewZealandCompaniesA,StatementOfDistributionToBeneficiary#IncomeTaxPayAsYouGoWithholdingCreditForTaxWithheldWhereABNNotQuotedA,StatementOfDistributionToBeneficiary#IncomeTaxableMinorBeneficiaryA,StatementOfDistributionToBeneficiary#IncomeDistributionFrankedA,StatementOfDistributionToBeneficiary#IncomeTaxFrankingCreditsReceivedFromAustralianCompaniesA,StatementOfDistributionToBeneficiary#IncomeTaxPayAsYouGoWithholdingCreditForAmountsWithheldWhereTFNNotQuotedA,StatementOfDistributionToBeneficiary#IncomeTaxPayAsYouGoWithholdingCreditForTaxWithheldFromCloselyHeldTrustA,StatementOfDistributionToBeneficiary#IncomeCapitalGainsNetA,StatementOfDistributionToBeneficiary#CapitalGainsTotalA,StatementOfDistributionToBeneficiary#CapitalLossesTotalA,StatementOfDistributionToBeneficiary#TaxConcessionCapitalGainsDiscountTotalA,StatementOfDistributionToBeneficiary#TaxConcessionCapitalGainsDiscountAndSmallBusinessConcessionsTotalA,StatementOfDistributionToBeneficiary#CapitalGainsNonConcessionalManagedInvestmentTrustIncomeA,StatementOfDistributionToBeneficiary#CapitalGainsExcludedFromNonConcessionalManagedInvestmentTrustIncomeA,StatementOfDistributionToBeneficiary#IncomeTaxPayAsYouGoWithholdingCreditForCapitalGainsWithheldFromForeignResidentsA,StatementOfDistributionToBeneficiary#IncomeTaxAttributedForeignIncomeA,StatementOfDistributionToBeneficiary#IncomeInternationalDealingsNetA,StatementOfDistributionToBeneficiary#IncomeInternationalDealingsTaxOffsetA,StatementOfDistributionToBeneficiary#TaxOffsetClaimNationalRentalAffordabilitySchemeEntitlementA,StatementOfDistributionToBeneficiary#IncomeTaxExplorationCreditsDistributedA,StatementOfDistributionToBeneficiary#IncomeSmallBusinessEntityNetA,StatementOfDistributionToBeneficiary#BeneficiaryShareA,StatementOfDistributionToBeneficiary#NonConcessionalManagedInvestmentTrustA,StatementOfDistributionToBeneficiary#ExcludedFromNonConcessionalManagedInvestmentTrustA,ShareOfIncomePrimaryProduction,StatementOfDistributionToBeneficiary#BeneficiaryShareA,StatementOfDistributionToBeneficiary#NonConcessionalManagedInvestmentTrustA,StatementOfDistributionToBeneficiary#ExcludedFromNonConcessionalManagedInvestmentTrustA,ShareOfIncomeNonPrimaryProduction,EarlyStageVentureTaxOffsetTaxOffsetClaimNonRefundableOtherA,EarlyStageInvestorTaxOffsetTaxOffsetClaimNonRefundableOtherA,StatementOfDistributionToBeneficiary#InternationalDealingsAssessableIncomeNonResidentBeneficiaryNonTrusteeA,StatementOfDistributionToBeneficiary#InternationalDealingsAssessableIncomeNonResidentBeneficiaryTrusteeA,NonResidentAdditionalInformation,Information,AnnualTrusteePaymentReportInformationIncomeTaxPayAsYouGoWithholdingCreditForTaxWithheldFromCloselyHeldTrustA,StatementOfDistributionToBeneficiary,StatementOfDistributionToBeneficiaryCollection,RP";

    }
}