在XML文件中查找节点

编程入门 行业动态 更新时间:2024-10-13 20:19:41
在XML文件中查找节点 - 在C#中提高性能(Find a node in an XML file - performance improvement in C#)

假设我需要使用C#在XML文件中查找特定节点。

<node attribute="my-target-attribute">

“my-target-attribute”是运行时的变量输入。

该节点在XML文件中没有特定的位置,我基本上只需要扫描整个XML层次结构,直到找到具有匹配属性的节点。

有什么办法可以预处理XML,因此找到节点会更快吗? 我需要保持原来的XML结构。 XML文件可能有10,000个节点。

Say I need to find a particular node in an XML file, using C#.

<node attribute="my-target-attribute">

"my-target-attribute" is a variable input at runtime.

The node is in no particular place in the XML file, I basically just need to scan the entire XML hierarchy until I find a node with the matching attribute.

Is there any way I can pre-process the XML so finding the node will be faster? I need to keep the original XML structure in place. The XML file could potentially have 10,000 nodes.

最满意答案

您当然可以对XML进行预处理以加快查找速度:

Dictionary<string, XmlElement> elementMap = new Dictionary<string, XmlElement>(); AddElementToMap(doc.DocumentElement, elementMap); ... private void AddElementToMap(XmlElement elm, Dictionary<string, XmlElement> elementMap) { elementMap[elm.GetAttribute("attribute")] = elm; foreach (XmlElement child in elm.SelectNodes("node")) { AddElementToMap(child, elementMap); } }

一旦你完成了这个,查找很简单:

XmlElement elm = elementMap[value];

该代码假设文档中的每个元素都被命名为“node”,每个元素都有一个名为“attribute”的属性,并且所有属性值都是唯一的。 如果这些条件中的任何一条不真实,代码就会更复杂,但并非如此。

You can certainly preprocess the XML to make lookups faster:

Dictionary<string, XmlElement> elementMap = new Dictionary<string, XmlElement>(); AddElementToMap(doc.DocumentElement, elementMap); ... private void AddElementToMap(XmlElement elm, Dictionary<string, XmlElement> elementMap) { elementMap[elm.GetAttribute("attribute")] = elm; foreach (XmlElement child in elm.SelectNodes("node")) { AddElementToMap(child, elementMap); } }

Once you've done this, a lookup is simple:

XmlElement elm = elementMap[value];

That code assumes that every element in your document is named "node", that every one has an attribute named "attribute", and that all of the attribute values are unique. The code's more complicated if any of those conditions are untrue, but not exceptionally so.

更多推荐

本文发布于:2023-08-04 22:20:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1423416.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:节点   文件   XML

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!