开发者

Loading a XML, but for asp.net 2.0

开发者 https://www.devze.com 2022-12-28 11:38 出处:网络
I need to load an XML document into my Dictionary<string,string> object. XML looks like: <nodes>

I need to load an XML document into my Dictionary<string,string> object.

XML looks like:

<nodes>
<node id="123">
   <text>text goes here</text>
</node>
</nodes>

How can I do this开发者_如何学Go using XmlDocument?

I want readability over performance, and I find XmlReader to be hard to read b/c you have to keep checking the node type.


Assuming ID is the key and the value of the <text> node is the value, you can use LINQ:

XDocument xDoc;
using(StringReader sr = new StringReader("thexml"))
{
    xDoc = XDocument.Load(sr);
}
myDictionary = xDoc.Descendants("node").ToDictionary(x => x.Attribute("id").Value, x => x.Descendants("text").First().Value);


Well, there is a reason why XML parsing has improved since 2.0, but if you just want a sample that parses that fragment without using XmlReader, this should work. I'm sure there are other ways of doing this:

XmlDocument doc = new XmlDocument();
doc.LoadXml(@"<nodes><node id=""123""><text>text goes here</text></node><node id=""321""><text>more text goes here</text></node></nodes>");

foreach (XmlNode nodes in doc.GetElementsByTagName("nodes"))
{
    foreach (XmlNode node in nodes.ChildNodes)
    {
        XmlNodeList list = node.SelectNodes("text");
        if (list.Count > 0)
        {
            Console.Write("{0}='{1}'\n", node.Attributes["id"].Value, list[0].InnerText);
        }
    }
}
Console.WriteLine("Done.");
Console.ReadKey();
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号