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.

2
  • why are you serializing it that way? Commented Feb 12, 2019 at 3:14
  • I got it from here: stackoverflow.com/questions/13171525/… and for me is the easiest way as I am also working with json format. Commented Feb 12, 2019 at 3:23

1 Answer 1

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"];
Sign up to request clarification or add additional context in comments.

3 Comments

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?
You should check keys in the dictionary to make sure that there is exactly your expected attribute.
Beat me to it. I used List<string> keys = new List<string>(((IDictionary<string, object>)obj.Message).Keys) Thanks for the help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.