PinballWizard
PinballWizard

Reputation: 141

OutOfMemoryException when trying to import xml to android

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.

Upvotes: 3

Views: 368

Answers (1)

user12267069
user12267069

Reputation:

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

Upvotes: 4

Related Questions