我正在尝试从简单的
XML文档读取元素值并将它们绑定到一个对象,但是我遇到了我的XML文档的问题.我已经验证了它,并且可以确认文档本身没有问题,但是扩展了结果:
var nodes = from xDoc in xml.Descendants("RewriteRule") select xmlSerializer.Deserialize(xml.CreateReader()) as Url;
内部异常读取< RewriteRules xmlns =''>没想到.
我不确定我在这里做错了什么?
我的XML如下:
<?xml version="1.0" encoding="utf-8" ?> <RewriteRules> <RewriteRule> <From>fromurl</From> <To>tourl</To> <Type>301</Type> </RewriteRule> </RewriteRules>
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; }
我的Url对象类: –
[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; } }
谁能看到我在这里做错了什么?
谢谢
解决方法
我不太熟悉from select语句,但是你似乎只是传入xml,这是整个XDocument,而不是你的RewriteRule的XElement.这就是为什么你得到RewriteRules未知的错误消息–XmlSerializer需要一个RewriteRule.
我设法使用LINQ重写你的代码(但是如果你知道如何从select语句中获取单个元素,那么它应该同样有效).
这应该给你正确的结果 – rr是从后代返回的XElement:
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; }