简体   繁体   中英

How to get deserialized xml attribute from dynamic object

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.

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"];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM