2

再会,

我一直在玩 ToDicationary() 扩展方法

var document = XDocument.Load(@"..\..\Info.xml");
XNamespace ns = "http://www.someurl.org/schemas";

var myData = document.Descendants(ns + "AlbumDetails").ToDictionary
    (
        e => e.Name.LocalName.ToString(),
        e => e.Value
    );

Console.WriteLine("Writing music...");
foreach (KeyValuePair<string, string> kvp in myData)
{
    Console.WriteLine("{0} = {1}", kvp.Key, kvp.Value);
}

使用以下 XML 数据:

<?xml version="1.0" encoding="UTF-8"?>
<Database xmlns="http://www.someurl.org/schemas">
    <Info>
        <AlbumDetails>
            <Artist>Ottmar Liebert</Artist>
            <Song>Barcelona Nights</Song>
            <Origin>Spain</Origin>
        </AlbumDetails>
    </Info>
</Database>

而且我没有得到我想要的输出。相反,我得到了这个:

Writing music...
AlbumDetails = Ottmar LiebertBarcelona NightsSpain

相反,我想要 myData("Artist") = "Ottmar Liebert" 等...

有没有可能与后代有关?

TIA,

科森

4

2 回答 2

2

以下将简单地获取AlbumDetails节点:

document.Descendants(ns + "AlbumDetails")

您想要它的直接后代(子节点) - 因为这些也是元素:

document.Descendants(ns + "AlbumDetails").Elements()

整行将是:

var myData = document.Descendants(ns + "AlbumDetails")
             .Elements().ToDictionary(
                                      e => e.Name.LocalName.ToString(),
                                      e => e.Value
                                     );
于 2012-08-16T19:48:21.200 回答
1

试试这个。

string s = "<data><resource key=\"123\">foo</resource><resource key=\"456\">bar</resource><resource key=\"789\">bar</resource></data>"; 
XmlDocument xml = new XmlDocument(); 
xml.LoadXml(s); 
XmlNodeList resources = xml.SelectNodes("data/resource"); 
SortedDictionary<string,string> dictionary = new SortedDictionary<string,string>(); 
foreach (XmlNode node in resources){ 
    dictionary.Add(node.Attributes["key"].Value, node.InnerText); 
} 
于 2012-08-16T19:50:29.673 回答