加载 XML,但适用于 asp.net 2.0

发布于 2024-08-31 00:03:45 字数 324 浏览 3 评论 0原文

我需要将 XML 文档加载到我的 Dictionary中对象。

XML 看起来像:

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

如何使用 XmlDocument 执行此操作?

我想要可读性而不是性能,并且我发现 XmlReader 很难阅读,因为您必须不断检查节点类型。

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 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

甜宝宝 2024-09-07 00:03:45

假设 ID 是键, 节点的值是值,则可以使用 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);

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);
四叶草在未来唯美盛开 2024-09-07 00:03:45

好吧,XML 解析自 2.0 以来得到了改进,这是有原因的,但如果您只想要一个不使用 XmlReader 解析该片段的示例,那么这应该可行。我确信还有其他方法可以做到这一点:

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();

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();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文