Exception in reading XML file

Asked

Viewed 589 times

2

I’ve been trying to fix this error in reading XML for weeks. I’m creating an app for Windows Phone 8 in C#. The moment I click on a subject and present the page with a listbox.

An Exception of type 'System.Argumentnullexception' occurred in mscorlib.ni.dll but was not handled in user code

The error occurs in this line of code:

 XDocument xdoc = XDocument.Parse(xml);

How can I solve this problem?

  • 2

    It is better to paste the code than a screenshot. You can [Edit] the question to include more details. I still have to tag the language too, I don’t know what it is...

  • 1

    What is the value of xml? This variable is null?

  • xml Carlos, will read the file . xml, then create a parser and generate a list of contents in the file.

  • The error occurs in the Xdocument.Parse(xml line)?

3 answers

1

I’m posting an example of how to read an xml from disk and deserialize it to a class. This way you don’t have to pick each item manually. This works on an old project I have here. Let’s go for the use explanations.

This is the template of my xml example.

<Pages> 
  <Page>
    <Name>Page 1</Name>
    <Url>http://www.google.com</Url>
    <XPathExpression></XPathExpression>
  </Page>
  <Page>    
    <Name>Page 2</Name>
    <Url></Url>
    <XPathExpression></XPathExpression>
  </Page>  
</Pages>

This is a class I use to load the xml, serialize it and deserialize it.

public class UtilXML
    {
        //Private fields        

        //Public fields 
        public XmlDocument XmlDocument { get; set; }

        public UtilXML() { }

        public void LoadXMLByPath(string FilePath)
        {
            try
            {
                XmlDocument = new XmlDocument();
                XmlDocument.Load(FilePath);               
            }
            catch (System.Xml.XmlException e)
            {
                throw new System.Xml.XmlException(e.Message);

            }
        }

        public void SerializeToXml<T>(T obj, string FileName)
        {
            XmlSerializer XmlSerializer = new XmlSerializer(typeof(T));
            FileStream FileStream = new FileStream(FileName, FileMode.Create);
            XmlSerializer.Serialize(FileStream, obj);
            FileStream.Close();
        }

        public T DeserializeFromXml<T>(string StringXML)
        {
            T Result;
            XmlSerializer XmlSerializer = new XmlSerializer(typeof(T));
            using (TextReader TextReader = new StringReader(StringXML))
            {
                Result = (T)XmlSerializer.Deserialize(TextReader);
            }
            return Result;
        }
    }

Essas são as classes que representam meu xml. Repare nos atributos que decoram essa classe. Eles tem os mesmos nomes dos elementos do xml.

[XmlRoot("Pages")]
    public sealed class Pages
    {
        [XmlElement("Page")]
        public List<Page> Items { get; set; }

        public Pages() 
        {
            Items = new List<Page>(); 
        }
    }
    public sealed class Page
    {
        [XmlElement("Name")]
        public string Name { get; set; }
        [XmlElement("Url")]
        public string Url { get; set; }
        [XmlElement("XPathExpression")]
        public string XPathExpression { get; set; }
    }

Example of use:

Load xml

UtilXML.LoadXMLByPath(@"C:\temp\Pages.xml");

Deserialize for the Pages class.

Pages = this.UtilXML.DeserializeFromXml<Pages>(this.UtilXML.XmlDocument.InnerXml);
  • Thanks man. I got it sorted !!!

1

Hoping it is relevant, if the problem is related to an empty value there is an alternative. Create an extension method.

Create a class with methods like this

public static class MetodosExtensao
{
    public static string ElementValueOrEmpty(this XElement element)
    {
        if (element != null)
            return element.Value;

        return "";
    }
}

In this case it is the reading of a String, I make one for each type of item.

In the class that will read xml add the class as the extension methods

using MetodosExtensao;

and the XML reading will be as below:

XDocument r; //aqui irá receber o xml     
IList<Classe> Lista = (from retorno in r.Descendants("Data").Elements("values")
                                                 select new Classe
                                                 {
                                                     nome = retornoBusca.Element("nome").ElementValueOrEmpty()
                                                 }).ToList();

That’s it. That’s the procedure I use, I’m beginner so sorry for any error in the answer or in the code.

0

It is almost certain that the xml variable is null for some reason. Consider validating its value before using it to instantiate the Xdocument object.

  • Thanks for the tip, but I don’t think I can... Check this out: // le the XML file // String xml = Utils.readFile("Resources xml eventos_" + type + ".xml"); // It is receiving something, in this case the file path

  • The problem is that this function is customized, it is part of your code. There may be some unwanted behavior happening within it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.