Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue de-serializing XML to Object - There is an error in XML document (0, 0)

I'm trying to read in element values from a simple XML doc and bind these to an object however I'm running into problems with my XML document. I have validated it and can confirm there are no issues with the document itself however expanding the results on the line:

var nodes = from xDoc in xml.Descendants("RewriteRule")
                select xmlSerializer.Deserialize(xml.CreateReader()) as Url;

Show "There is an error in XML document (0, 0)"

The inner exceptions reads <RewriteRules xmlns=''> was not expected.

I'm not sure what I'm doing wrong here?

My XML is below:

<?xml version="1.0" encoding="utf-8" ?>
<RewriteRules>
    <RewriteRule>
        <From>fromurl</From>
        <To>tourl</To>
        <Type>301</Type>
    </RewriteRule>
</RewriteRules>

The code that loads the XML file and attempts to de-serialize it: -

public static UrlCollection GetRewriteXML(string fileName)
{
    XDocument xml = XDocument.Load(HttpContext.Current.Server.MapPath(fileName));
    var xmlSerializer = new XmlSerializer(typeof(Url));

    var nodes = from xDoc in xml.Descendants("RewriteRule")
                select xmlSerializer.Deserialize(xml.CreateReader()) as Url;

    return nodes as UrlCollection;
}

My Url object class: -

[Serializable]
[XmlRoot("RewriteRule")]
public class Url
{
    [XmlElement("From")]
    public string From { get; set; }
    [XmlElement("To")]
    public string To { get; set; }
    [XmlElement("Type")]
    public string StatusCode { get; set; }

    public Url()
    {
    }

    public Url(Url url)
    {
        url.From = this.From;
        url.To = this.To;
        url.StatusCode = this.StatusCode;
    }
}

Can anyone see what I'm doing wrong here?

Thanks

like image 429
DGibbs Avatar asked Mar 14 '13 09:03

DGibbs


1 Answers

I'm not too familiar with the from select statement, but it seems you just pass in xml which is the whole XDocument, instead of the XElement that is your RewriteRule. That is why you get the error message that RewriteRules is unknown - the XmlSerializer expects a single RewriteRule.

I managed to rewrite your code using LINQ instead (but if you know how to get the single element from the from select statement, that should work equally well).

This should give you the correct result - rr is the XElement that is returned from Descendants:

public static IEnumerable<Url> GetRewriteXML()
{
    XDocument xml = XDocument.Load(HttpContext.Current.Server.MapPath(fileName));

    var xmlSerializer = new XmlSerializer(typeof(Url));

    var nodes = xml.Descendants("RewriteRule")
                .Select(rr => xmlSerializer.Deserialize(rr.CreateReader()) as Url);

    return nodes;
}
like image 134
default Avatar answered Sep 25 '22 20:09

default