2012-12-22 17 views
1

如何將整個XML文檔解析爲字典,我需要向正確的方向推一下。我的計劃是讓鍵爲路徑,每個嵌套類型都按「 - >」分隔。例如:將XDocument解析爲字典<string,string>

<Foo> 
    <Bar>3</Bar> 
    <Foo> 
     <Bar>10</Bar> 
    </Foo> 
</Foo> 

如果我想用得到的值我剛剛搶出來的字典:

string value = Elements["Foo->Bar"]; 

我真的不知道如何去通過每一個元素雖然遞歸。 任何幫助表示讚賞。

+0

的XML無所謂,因爲我基本上要經過的路徑字符串訪問它,我只是需要一種方法因爲它將這些XML元素解析爲一個字典,路徑是關鍵字。 – redcodefinal

回答

3

簡單的解決方案:

private static string GetElementPath(XElement element) 
    { 
     var parent = element.Parent; 
     if(parent == null) 
     { 
      return element.Name.LocalName; 
     } 
     else 
     { 
      return GetElementPath(parent) + "->" + element.Name.LocalName; 
     } 
    } 

    static void Main(string[] args) 
    { 
     var xml = @" 
      <Foo> 
       <Bar>3</Bar> 
       <Foo> 
        <Bar>10</Bar> 
       </Foo> 
      </Foo>"; 
     var xdoc = XDocument.Parse(xml); 
     var dictionary = new Dictionary<string, string>(); 
     foreach(var element in xdoc.Descendants()) 
     { 
      if(!element.HasElements) 
      { 
       var key = GetElementPath(element); 
       dictionary[key] = (string)element; 
      } 
     } 
     Console.WriteLine(dictionary["Foo->Bar"]); 
    } 
+0

非常棒!謝謝您的幫助。我不知道tom是如何檢查元素是否是父節點的。 – redcodefinal

0

XML文檔的另一種選擇,但不知道真正的結構

string data = "<Foo><Bar>3</Bar><Foo><bar>123</bar></Foo></Foo>"; 

    XDocument xdoc = XDocument.Parse(data); 
    Dictionary<string, string> dataDict = new Dictionary<string, string>(); 

    foreach (XElement xelement in doc.Descendants().Where(x => x.HasElements == false)) 
    { 
     int keyInt = 0; 
     string keyName = xelement.Name.LocalName; 

     while (dataDict.ContainsKey(keyName)) 
      keyName = xelement.Name.LocalName + "->" + keyInt++; 

     dataDict.Add(keyName, xelement.Value); 
    } 
0
public static void parse() 
    { 
     Stack<String> stck = new Stack<string>(); 
     List<String> nodes = new List<string>(); 
     Dictionary<String, String> dictionary = new Dictionary<string, string>(); 

     using (XmlReader reader = XmlReader.Create("path:\\xml.xml")) 
     { 

      while (reader.Read()) 
      { 
       if (reader.NodeType == XmlNodeType.Element) 
       { 

        stck.Push(reader.Name); 

       } 
       if (reader.NodeType == XmlNodeType.Text) 
       { 
        StringBuilder str = new StringBuilder(); 
        if (stck.Count > 0) 
         nodes = stck.ToList<String>(); 
        //List<String> _nodes ; 
        nodes.Reverse(0,nodes.Count); 
        foreach (String node in nodes) 
         str.Append(node + " --> "); 

        dictionary.Add(str.ToString(), reader.Value); 
        str.Clear(); 
       } 
       if (reader.NodeType == XmlNodeType.EndElement) 
       { 

        stck.Pop(); 

       } 
      } 
     } 

     foreach (KeyValuePair<String, String> KVPair in dictionary) 
      Console.WriteLine(KVPair.Key + " : " + KVPair.Value); 
     Console.Read(); 
    } 
相關問題