C# 之 dynamic object

近来在用CSOM解析Web Part属性,发现读取带namespace的XML还真是有点恶心,说白了就是懒得去深究,想啊,要是能变成类似JSON的东西就好了,

想起来.net4.0就神一般存在的 dynamic对象,有可能会带来惊喜,

果不然

<?xml version="1.0" encoding="utf-8" ?>

<contacts>

  <contact id='1'>

    <firstName>Michael</firstName>

    <lastName>Jordan</lastName>

    <age>40</age>

    <dob>1965</dob>

    <salary>100.35</salary>

  </contact>

  <contact id='2'>

    <firstName>Scottie</firstName>

    <lastName>Pippen</lastName>

    <age>38</age>

    <dob>1967</dob>

    <salary>55.28</salary>

  </contact>

</contacts>
public class XmlToDynamic

{

  public static void Parse(dynamic parent, XElement node)

  {

    if (node.HasElements)

    {

      if (node.Elements(node.Elements().First().Name.LocalName).Count() > 1)

      {

        //list

        var item = new ExpandoObject();

        var list = new List<dynamic>();

        foreach (var element in node.Elements())

        {            

          Parse(list, element);            

        }

 

        AddProperty(item, node.Elements().First().Name.LocalName, list);

        AddProperty(parent, node.Name.ToString(), item);

      }

      else

      {

        var item = new ExpandoObject();

 

        foreach (var attribute in node.Attributes())

        {

          AddProperty(item, attribute.Name.ToString(), attribute.Value.Trim());

        }

 

        //element

        foreach (var element in node.Elements())

        {

          Parse(item, element);

        }

 

        AddProperty(parent, node.Name.ToString(), item);

      }

    }

    else

    {

      AddProperty(parent, node.Name.ToString(), node.Value.Trim());

    }

  }

 

  private static void AddProperty(dynamic parent, string name, object value)

  {

    if (parent is List<dynamic>)

    {

      (parent as List<dynamic>).Add(value);

    }

    else

    {

      (parent as IDictionary<String, object>)[name] = value;

    }

  }

}
[Test]

public void Test()

{

  //read from text

  //var xDoc = XDocument.Parse(txt);

 

  //read from url

  //var request = WebRequest.Create(@"http://...") as HttpWebRequest;

  //request.Credentials = CredentialCache.DefaultNetworkCredentials;

  //var xDoc = XDocument.Load(request.GetResponse().GetResponseStream());

 

  //read from file

  var xDoc = XDocument.Load(new StreamReader("contacts.xml"));

 

  dynamic root = new ExpandoObject();

 

  XmlToDynamic.Parse(root, xDoc.Elements().First());

 

  Console.WriteLine(root.contacts.contact.Count);

  Console.WriteLine(root.contacts.contact[0].firstName);

  Console.WriteLine(root.contacts.contact[0].id);

}

我复制粘贴后开心的要死,一断点才发现也不是那么开心,后发现带Namespace的时候,要注意 Name 和Name.LocalName
尤其修改这一句用Name if (node.Elements(node.Elements().First().Name).Count() > 1)
还有气候的Name 变成 Name.LocalName
果然,服务端JSON出台了。

你可能感兴趣的:(dynamic)