简体   繁体   中英

'System.InvalidOperationException' occurred in System.Xml.dll

I try to parse the XML of the following website: PubMed

I'm using the following code to do the job:

public void SearchByURI(string keyword)
{
    string URI = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=pubmed&term=" + keyword;
    System.Xml.Serialization.XmlSerializer reader = new System.Xml.Serialization.XmlSerializer(typeof(eSearchResult));
    XmlReader xmlReader = XmlReader.Create(URI);
    eSearchResult result = new eSearchResult();
    result = (eSearchResult)reader.Deserialize(xmlReader);
}

But when I run the code, it crashes at the last line with the following exception:

An exception of type 'System.InvalidOperationException' occurred in System.Xml.dll but was not handled in user code. Additional information: There is an error in XML document (0, 0).

The class that the XML is supposed to be serialized to can be found at the following pastbin, a bit to large to be pasted in here. PasteBin link. This code has been generated by Visual Studio

So what I did to solve the following problem was to use XElement as suggestet by Jeroen Mostert.

First of all I created to extension methods as suggested in the following post like this:

public static XElement ToXElement<T>(this object obj)
    {
        using (var memoryStream = new MemoryStream())
        {
            using (TextWriter streamWriter = new StreamWriter(memoryStream))
            {
                var xmlSerializer = new XmlSerializer(typeof(T));
                xmlSerializer.Serialize(streamWriter, obj);
                return XElement.Parse(Encoding.ASCII.GetString(memoryStream.ToArray()));
            }
        }
    }

    public static T FromXElement<T>(this XElement xElement)
    {
        using (var memoryStream = new MemoryStream(Encoding.ASCII.GetBytes(xElement.ToString())))
        {
            var xmlSerializer = new XmlSerializer(typeof(T));
            return (T)xmlSerializer.Deserialize(memoryStream);
        }
    }

Then i changed the code above to the follwoing:

 public eSearchResult SearchByURI(string keyword)
    {
        string URI = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=pubmed&term=" + keyword;
        XElement xml = XElement.Load(URI);
        eSearchResult pubMedResult = xml.FromXElement<eSearchResult>();
        return pubMedResult; 
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM