假设我需要使用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.
更多推荐
发布评论