我有许多名称的XML,如列表:
<apelidos>
<apelido>Casmilo</apelido>
<apelido>Castro</apelido>
</apelidos>
我做了这样的模型:
namespace IdCel.Model
{
[XmlTypeAttribute(AnonymousType = true)]
public class apelidos
{
[XmlArray("apelidos")]
[XmlArrayItem("apelidos")]
public List<apelido> apelidosNomes { get; set; }
public apelidos()
{
apelidosNomes = new List<apelido>();
}
}
public class apelido
{
[XmlElement(ElementName = "apelido")]
public string apelidoNome { get; set; }
}
}
我的XmlSerializer
HttpWebRequest request = WebRequest.Create(uri) as HttpWebRequest;
XmlSerializer ser = new XmlSerializer(objetoLista.GetType());
WebResponse response = request.GetResponse();
var result = ser.Deserialize(response.GetResponseStream());
return result;
但它不起作用,我使用没有列表的XML执行相同的代码并且它工作正常
答案 0 :(得分:1)
如果您只需阅读apelido
代码的内容,则在使用Linq To XML时速度会更快。例如:
var xml = @"<apelidos>
<apelido>Casmilo</apelido>
<apelido>Castro</apelido>
</apelidos>";
var doc = XDocument.Parse(xml);
var apelidos = from apelido in doc.Descendants("apelido")
select apelido.Value;
这会为您提供一个包含所有名称的IEnumerable<string>
。
编辑:要从Web加载XML,您可以执行以下操作:
HttpWebRequest request = WebRequest.Create(uri) as HttpWebRequest;
WebResponse response = request.GetResponse();
var doc = XDocument.Load(response.GetResponseStream());
答案 1 :(得分:0)
现在它奏效了! 我这样做了:
[Serializable()]
public class apelidos
{
[System.Xml.Serialization.XmlElement("apelido")]
public List<string> apelido { get; set; }
}
而且:
HttpWebRequest request = WebRequest.Create(uri)
as HttpWebRequest;
XmlSerializer ser = new XmlSerializer(objetoLista.GetType());
WebResponse response = request.GetResponse();
var result = ser.Deserialize(response.GetResponseStream());
return result;