views:

363

answers:

5
+1  Q: 

Error in my XML?

I have the following code:

public class DeserializeAndCompare
{
    public static List<string> IntoXML()
    {
        List<string> PopList = new List<string>();

        XmlSerializer serializer = new XmlSerializer(PopList.GetType());
        string k = FileToolBox.position0;
        FileStream filestreamer = new FileStream(k.ToString(), FileMode.Open);
        PopList = (List<string>)serializer.Deserialize(filestreamer);
        filestreamer.Close();
        return PopList;

    }
}

I keep hitting an error with the line: PopList = (List)serializer.Deserialize(filestreamer);

The error: InvalidOperationException was unhandled, There is an error in XML document(1,1).

In this line: FileStream filestreamer = new FileStream(k, FileMode.open);

I am trying to reference the 0th position of an array that holds strings. I'm basically going thru my directory, finding any files with a .xml extension and holding the filename paths in an array.
Here is the code for my array:

public static class FileToolBox
{

    public static string position0;
    public static void FileSearch()
    {



        //string position0;

        //array holding XML file names
        string[] array1 = Directory.GetFiles(@"s:\project", "*.xml");

        Array.Sort(array1);
        Array.Reverse(array1);
        Console.WriteLine("Files:");
        foreach (string fileName in array1)
        {

            Console.WriteLine(fileName);

        }

        position0 = array1[0];

    }

    public static string Position0
    {
     get
        {
            return position0;
        }
        set
        {
            position0 = value;
        }

    }
    }

Am i missing something here? How do i get rid of this error?

Thanks in advance for the help.

+1  A: 

That error is specifically indicating that the XML file being read is malformed. You should start by posting your XML. Also, try opening the XML in Firefox, because it may point out the problem with the XML as well.

Jacob
+1  A: 

Your xml document is not well formed, you need to open your xml file up and analyze it.

There are multiple xml validators on the web, but here's one from w3schools.

Joseph
+3  A: 

Your XML file is not well formed, use a tool like XML Spy, XML notepad or open it up in IE and it will give you the error and the line it is on. You most likely have invalid characters like & somewhere in the file

SQLMenace
A: 

Give this a shot:

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace Util
{
    /// <summary>
    /// Not to be confused with System.Xml.Serialization.XmlSerializer, which this uses internally.
    /// 
    /// This will convert the public fields and properties of any object to and from an XML string, 
    /// unless they are marked with NonSerialized() and XmlIgnore() attributes.
    /// </summary>
    public class XMLSerializer
    {
        public static Byte[] GetByteArrayFromEncoding(Encoding encoding, string xmlString)
        {
            return encoding.GetBytes(xmlString);
        }

        public static String SerializeToXML<T>(T objectToSerialize)
        {
            return SerializeToXML(objectToSerialize, Encoding.UTF8);
        }

        public static String SerializeToXML<T>(T objectToSerialize, Encoding encoding)
        {
            StringBuilder sb = new StringBuilder();

            XmlWriterSettings settings =
                new XmlWriterSettings { Encoding = encoding, Indent = true };

            using (XmlWriter xmlWriter = XmlWriter.Create(sb, settings))
            {
                if (xmlWriter != null)
                {
                    new XmlSerializer(typeof (T)).Serialize(xmlWriter, objectToSerialize);
                }
            }

            return sb.ToString();
        }

        public static void DeserializeFromXML<T>(string xmlString, out T deserializedObject) where T : class
        {
            DeserializeFromXML(xmlString, new UTF8Encoding(), out deserializedObject);
        }

        public static void DeserializeFromXML<T>(string xmlString, Encoding encoding, out T deserializedObject) where T : class
        {
            XmlSerializer xs = new XmlSerializer(typeof(T));

            using (MemoryStream memoryStream = new MemoryStream(GetByteArrayFromEncoding(encoding, xmlString)))
            {
                deserializedObject = xs.Deserialize(memoryStream) as T;
            }
        }
    }
}


public static void Main()
{
    List<string> PopList = new List<string>{"asdfasdfasdflj", "asdflkjasdflkjasdf", "bljkzxcoiuv", "qweoiuslfj"};

    string xmlString = Util.XMLSerializer.SerializeToXML(PopList);

    XmlDocument xmlDoc = new XmlDocument();
    xmlDoc.LoadXml(xmlString);

    string fileName = @"C:\temp\test.xml";
    xmlDoc.Save(fileName);

    string xmlTextFromFile = File.ReadAllText(fileName);

    List<string> ListFromFile;

    Util.XMLSerializer.DeserializeFromXML(xmlTextFromFile, Encoding.Unicode, out ListFromFile);

    foreach(string s in ListFromFile)
    {
        Console.WriteLine(s);
    }
}

Check the output XML file and see what the encoding is, and compare that to what encoding you're trying to read in. I got caught with this problem before because I use a StringBuilder to output the XML string, which writes in UTF-16, but I was trying to read in as UTF-8. Try using Encoding.Unicode and see if that works for you.

Chris Doggett
A: 

Your code will only work with XML files which have the following structure...

<?xml version="1.0" encoding="utf-16"?>
<ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt;
  <string>Hello</string>
  <string>World</string>
</ArrayOfString>
Thomas Levesque