XDocument from string 有一个元素,需要字典

XDocument from string has one element, need toDictionary

我有一个正在解析为 XDocument 的 xmlString:

xmlString = 
"<TestXml>" +
   "<Data>" +
      "<leadData>" +
        "<Email>testEmail@yahoo.ca</Email>" +
        "<FirstName>John</FirstName>" +
        "<LastName>Doe</LastName>" +
        "<Phone>555-555-5555</Phone>" +
        "<AddressLine1>123 Fake St</AddressLine1>" +
        "<AddressLine2></AddressLine2>" +
        "<City>Metropolis</City>" +
        "<State>DC</State>" +
        "<Zip>20016</Zip>" +
     "</leadData>" +
  "</Data>" +
"</TestXml>"

我将字符串解析为 XDocument,然后尝试遍历节点:

XDocument xDoc = XDocument.Parse(xmlString);
Dictionary<string, string> xDict = new Dictionary<string, string>();

//Convert xDocument to Dictionary
foreach (var child in xDoc.Root.Elements())
{
      //xDict.Add();
}

这只会迭代一次,而且一次迭代似乎包含所有数据。我意识到我做错了什么,但谷歌搜索后我不知道是什么。

在 foreach 循环中尝试 xDoc.Root.Descendants() 而不是 xDoc.Root.Elements()

你的root只有一个childData,因此它只迭代一次

var xDict = XDocument.Parse(xmlString)
            .Descendants("leadData")
            .Elements()
            .ToDictionary(e => e.Name.LocalName, e => (string)e);