问题解串行化XML到对象 - 有一个在XML文档的错误(0,0) [英] Issue de-serializing XML to Object - There is an error in XML document (0, 0)
问题描述
我想从一个简单的XML文档读取元素值,并绑定到这些物体但是我遇到问题,我的XML文档。我已经验证它,可以确认有与文档但是本身扩大就行了,结果没有问题:
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;
显示的有在XML文档的错误(0,0)的
的内部异常读<规则集的xmlns =''>是没有预料到。
我不知道我在做什么错在这里?
I'm not sure what I'm doing wrong here?
我的XML是如下:
<?xml version="1.0" encoding="utf-8" ?>
<RewriteRules>
<RewriteRule>
<From>fromurl</From>
<To>tourl</To>
<Type>301</Type>
</RewriteRule>
</RewriteRules>
在code加载XML文件,并试图反序列化: -
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?
感谢
推荐答案
我不是太熟悉的从选择
语句,但似乎你只是传递 XML
这是整个的XDocument
,而不是的XElement
的是你的重写规则
。这就是为什么你得到错误信息的规则集
是未知的 - 在的XmlSerializer
只需要一个重写规则
。
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
.
我设法用重写你的code LINQ
来代替(但如果你知道如何从选择获取单个元素从
语句,应该同样有效)。
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).
这应该给你正确的结果 - RR
是的XElement
从返回的后人
:
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;
}
这篇关于问题解串行化XML到对象 - 有一个在XML文档的错误(0,0)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!