user829174
user829174

Reputation: 6362

cannot cast expression of type 'System.Xml.Linq.XElement to type XXX

I am getting compiler error: cannot cast expression of type 'System.Xml.Linq.XElement to type AutomationStatusType What am i doing wrong?

xml:

<Status>
    <Version>33</Version>
    <Status>Running</Status>
</Status>

query:

var query = (from status in doc.Descendants("Status")
    select new AutomationStatus
            {
                Version = (string)status.Element("Version"),
                Status = (AutomationStatusType)status.Element("Status"),
            });

classes:

public class AutomationStatus
{
    [XmlAttribute]
    public string Version { get; set; }
    [XmlElement]
    public AutomationStatusType Status { get; set; }
}


[DataContract]
public enum AutomationStatusType
{
    [EnumMember]
    Idle,
    [EnumMember]
    Running
}    

Edit: after reading your comments, i indeed added the following casing:

Status = Enum.Parse(typeof(AutomationStatusType), (string)status.Element("Status")),

Now i am getting a compilation error: Cannot convert type 'System.Xml.Linq.XElement' to 'Verint.AP2.Manager.AutomationStatusType'

However, if i create an anonymous class i am being able to get rid of the errors:

    var query = (from status in doc.Descendants("AutomationStatus")
                 select new /*AutomationStatus*/
                            {
                                Version = (string)status.Element("Version"),
                                Status = Enum.Parse(typeof(AutomationStatusType), (string)status.Element("Status")),
                                TimeStamp = (DateTime) status.Element("TimeStamp")
                            });

What can be the issue, how can i create the class (non anonymous?) Thanks!

Upvotes: 1

Views: 4930

Answers (3)

dtb
dtb

Reputation: 217351

There is no type conversion operator between XElement and your enum. You need to convert the XElement to a string and parse the string to the enum:

{
    Version = (string)status.Element("Version"),
    Status = (AutomationStatusType)Enum.Parse(
        typeof(AutomationStatusType), (string)status.Element("Status")),
}

Upvotes: 2

Mharlin
Mharlin

Reputation: 1705

Use the following snippet when you parse the status instead of the Row you have now.

Status = Enum.Parse(typeof(AutomationStatusType), status.Element("Status")

Upvotes: 3

dice
dice

Reputation: 2880

though your code is not showing it im guessing that you are loading an XmlDoc or something.

use XmlSerializer instead.

something along the lines of:

 XmlSerializer serializer = new XmlSerializer(typeof(AutomationStatus));
 FileStream fs = new FileStream(filename, FileMode.Open);
 AutomationStatus x;
 x = (AutomationStatus) serializer.Deserialize(fs);

Upvotes: 0

Related Questions