2015-04-03 82 views
0

所以我有一個具有多個層級的這樣一個XML文檔:遞歸/動態添加XML屬性到單一動態對象

<root> 
<Client id='1' name='bob'> 
    <health id='1'> 
      <ex id='2'\> 
      <ex id='3' \> 
    </health> 
</Client> 
<Client id='1' name='bob'> 
    <health id='1'> 
      <ex id='2'\> 
      <ex id='3' \> 
    </health> 
</Client> 
</root> 

我試圖遞歸經過XML文檔和每個屬性的ExpandoObject並遞歸地將所有子節點添加到ExpandoObject中。因此,上述xml的最終結果將包含具有客戶端屬性的ExpandoObject以及其內部具有健康屬性的ExpandoObject,以及具有健康ExpandoObject中的'ex'屬性的2個expandoObjects。所以它就像將多維詞典中的XML文檔放入ExpandoObject一樣。

我在遞歸方面遇到了很多麻煩,它令我困惑,而我似乎無法得到它的工作。有誰知道我如何像遞歸遍歷XDocument,併爲每個子層添加一個ExpandoObject自身,但是如果它的深度級別相同,則將多個ExpandoObjects添加到它上面的對象上?

我知道,因爲我也很迷茫,但最終目標應該是這個樣子,這可能混淆你:

對象ASD = [客戶端的屬性] +(ExpandoObject asd2 = [健康的特性] +(ExpandoObject前EX2的+ ExpandoObject asd4 =屬性)

回答

0

的asd3 =性能,我發現一些代碼,已經爲我工作至今。

public static class XmlDocumentExtension 
{ 
    public static dynamic ToObject(this XmlDocument document) 
    { 
     XmlElement root = document.DocumentElement; 
     return ToObject(root, new ExpandoObject()); 
    } 

    private static dynamic ToObject(XmlNode node, ExpandoObject config, int count = 1) 
    { 
     var parent = config as IDictionary<string, object>; 
     foreach (XmlAttribute nodeAttribute in node.Attributes) 
     { 
      var nodeAttrName = nodeAttribute.Name.ToString(); 
      parent[nodeAttrName] = nodeAttribute.Value; 
     } 
     foreach (XmlNode nodeChild in node.ChildNodes) 
     { 
      if (IsTextOrCDataSection(nodeChild)) 
      { 
       parent["Value"] = nodeChild.Value; 
      } 
      else 
      { 
       string nodeChildName = nodeChild.Name.ToString(); 
       if (parent.ContainsKey(nodeChildName)) 
       { 
        parent[nodeChildName + "_" + count] = ToObject(nodeChild, new ExpandoObject(), count++); 
       } 
       else 
       { 
        parent[nodeChildName] = ToObject(nodeChild, new ExpandoObject()); 
       } 
      } 
     } 
     return config; 
    } 

    private static bool IsTextOrCDataSection(XmlNode node) 
    { 
     return node.Name == "#text" || node.Name == "#cdata-section"; 
    } 
}