J'ai un fichier XML avec un certain nombre de Unit
s:Comment puis-je lire un élément XML complet ici?
<Unit Name="Length">
<Prefix Char="c"
IsSelected="false"
Factor="1"/>
<Prefix Char="d"
IsSelected="true"
Factor="104"/>
</Unit>
Je veux lire un objet entier:
public static Dictionary<string, Unit> Units { get; set; }
public class Prefix
{
public Func<double, double> fnc = null;
public Prefix(string c, double f, bool i, bool ifix = false,string fn = null)
{
Char = c;
Factor = f;
IsFixed = ifix;
Unit.funcs.TryGetValue(fn, out fnc);
}
public bool IsSelected { get; set; }
public bool IsFixed { get; set; }
public double Factor { get; set; }
public string Char { get; set; }
}
public Unit() { }
public Unit(string n, List<Prefix> p)
{
_name = n;
Prefixes = p;
}
private List<Prefix> _prefixes;
public List<Prefix> Prefixes
{
get { return _prefixes; }
set { _prefixes = value; }
}
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
....
}
J'ai maintenant ceci:
Form.Units = (data.Descendants("Unit").Select(x => new Unit
(
x.Attribute("Name").Value,
(List<Prefix>) x.Descendants("Prefix").Select(p => new Prefix(
p.Attribute("Char").Value,
Convert.ToDouble(p.Attribute("Factor").Value),
p.Attribute("IsSelected").Value == "true",
p.Attribute("IsFixed").Value == "true",
p.Attribute("Func").Value)
)
)
)
).ToDictionary(x => x.Name, x => x);
et obtenir l'erreur suivante:
"Unable to cast object of type 'WhereSelectEnumerableIterator
2[System.Xml.Linq.XElement,DD.Prefix]' to type 'System.Collections.Generic.List
1[DD.Prefix]'."
Apparemment, il y a quelque chose de mal avec le (List<Prefix>)
Qu'est-ce que la requête devra être alors? Comment puis-je obtenir des choses dans la liste <>?
.
Il serait plus simple d'appeler '.ToList()' sur votre sous-requête. Comme ceci: 'x.Descendants (" Préfixe "). Sélectionnez (p => nouveau préfixe (....). ToList()' – Tim
Notez également que vous pouvez obtenir des exceptions de référence NULL lorsque les attributs (ou éléments) ne sont pas Vous pouvez éviter cela en utilisant un transtypage explicite dans 'string' (qui retournera null si l'élément/l'attribut est introuvable), par exemple' (chaîne) p.Attribute ("Char") 'ou' Convert.ToDouble ((chaîne) p.Attribute ("Factor")) '. – Tim