3

i have xml file 230 mb big with 230 million length when i try to import the file to my android using an app that we made but when attempting readtoend string into variable im getting an error :

System.outofmemoryexception : out of memory at (wrapper managed-to-native) system.string.fastallocatestring(int) at system.text.stringbuilder.tostring()

here's the following code

var documentsPath = Android.OS.Environment.ExternalStorageDirectory.ToString();
            var dirName = System.IO.Path.Combine(documentsPath.ToString(), "Stock");

            var filePath = System.IO.Path.Combine(dirName, "Data.xml");
            TextReader tr = new StreamReader(filePath);
            string result = tr.ReadToEnd();
            tr.Close();

            var st = new XStreamingElement(filePath);

            return result;

can anyone help, thanks in advance.

PinballWizard
  • 129
  • 1
  • 10
  • 1
    Possible duplicate of [Getting OutOfMemoryException in Xamarin](https://stackoverflow.com/questions/36835790/getting-outofmemoryexception-in-xamarin) – Fahim Abrar Oct 24 '19 at 06:34
  • 1
    Take a look at [What is the best way to parse (big) XML in C# Code?](https://stackoverflow.com/q/676274) and [Reading Xml with XmlReader in C#](https://stackoverflow.com/q/2441673). – dbc Oct 24 '19 at 07:06

1 Answers1

4

Try using XMLTextReader class instead as the example below:

XmlTextReader myTextReader = new XmlTextReader(filename);
myTextReader.WhitespaceHandling = WhitespaceHandling.None;
while (myTextReader.Read())
{
    if (myTextReader.NodeType == XmlNodeType.Element &&
        myTextReader.LocalName == "Reward" &&
        myTextReader.IsStartElement() == true)
        {
            ProcessRewardNode(myTextReader);
                myTextReader.Skip();
    }
}

Here is the method implementation of ProcessRewardNode:

private void ProcessRewardNode(XmlTextReader RewardReader)
{
    XmlDocument RewardXmlDoc = new XmlDocument();
    RewardXmlDoc.LoadXml(RewardReader.ReadOuterXml());
    // we can use xpath as below
    myID = RewardXmlDoc.SelectSingleNode("Reward/myID").InnerText;
}

for more info visit XMLTextReader's official documentation