5

I can get the element innertext from expandoobject without any problem. I can't figure out how to get the attribute's value.

By doing Console.WriteLine(obj.Message.Body), I can get the expected string inside the body element.

    private void TestXML()
    {
        string xmlString = @"<?xml version=""1.0"" encoding=""utf-8""?><Message important=""yes"" recevied=""2019-2-12""><Body>Hi there fella!</Body></Message>";
        XDocument doc = XDocument.Parse(xmlString);
        string json = JsonConvert.SerializeXNode(doc);
        dynamic obj = JsonConvert.DeserializeObject<ExpandoObject>(json);

        Console.WriteLine(obj.Message);

    }

I did a debug and and under obj.Message I can see 3 fields:

  • @important with value "yes"
  • @received with value "2019-2-12"
  • Body with value "Hi there fella!"

Is there a way to retrieve the first 2 fields' values with a @ prefix? I have no idea how to deal with this @ character on dynamic objects.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445

1 Answers1

5

To deal with special characters, such as "@" in dynamic object, you must cast it to ` (IDictionary). And then you can get the recevied attribute as bellow:

var received = ((IDictionary<string, object>)obj.Message)["@recevied"];
Nhan Phan
  • 1,262
  • 1
  • 14
  • 32
  • This worked. I can successfully get the value. What if I want to return the attribute "recevied" (just realized the spelling mistake), how am I going to do that? – Marcus Aurelius Feb 12 '19 at 06:23
  • You should check keys in the dictionary to make sure that there is exactly your expected attribute. – Nhan Phan Feb 12 '19 at 06:42
  • 2
    Beat me to it. I used `List keys = new List(((IDictionary)obj.Message).Keys)` Thanks for the help. – Marcus Aurelius Feb 12 '19 at 06:54