Pregunta

Tengo el siguiente código:

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;

    }
}

Sigo golpeando un error con la línea:     PopList = (List) serializer.Deserialize (filestreamer);

El error: InvalidOperationException no fue manejado, hay un error en el documento XML (1,1).

En esta línea:     FileStream filestreamer = nuevo FileStream (k, FileMode.open);

Estoy intentando hacer referencia a la posición 0 de una matriz que contiene cadenas. Básicamente, voy a través de mi directorio, encontrando cualquier archivo con una extensión .xml y manteniendo las rutas de nombre de archivo en una matriz.
Aquí está el código para mi matriz:

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;
        }

    }
    }

¿Me estoy perdiendo algo aquí? ¿Cómo me deshago de este error?

Gracias de antemano por la ayuda.

¿Fue útil?

Solución

Su archivo XML no está bien formado, use una herramienta como XML Spy, Bloc de notas XML o ábralo en IE y le dará el error y la línea en la que se encuentra. Lo más probable es que tenga caracteres no válidos como & amp; en algún lugar del archivo

Otros consejos

Ese error indica específicamente que el archivo XML que se está leyendo tiene un formato incorrecto. Debes empezar por publicar tu XML. Además, intente abrir el XML en Firefox, ya que puede señalar el problema con el XML también.

Su documento XML no está bien formado, debe abrir su archivo XML y analizarlo.

Hay varios validadores xml en la web, pero aquí hay uno de w3schools .

Dale una oportunidad a esto:

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);
    }
}

Verifique el archivo XML de salida y vea qué es la codificación, y compárela con la codificación que está intentando leer. Me sorprendió este problema antes porque uso un StringBuilder para generar la cadena XML, que escribe UTF-16, pero estaba intentando leer como UTF-8. Intente usar Encoding.Unicode y vea si eso funciona para usted.

Su código solo funcionará con archivos XML que tengan la siguiente estructura ...

<?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">
  <string>Hello</string>
  <string>World</string>
</ArrayOfString>
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top