开发者

Find a node in an XML file - performance improvement in C#

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 pa开发者_如何学JAVArticular 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.


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.


You could use xslt to transform the xml so that the node is in a known depth. Then when you select with XPath, you can select accordingly without using the // operator.


With VTD-XML (http://vtd-xml.sf.net) you can index the XML document into VTD+XML, which eliminate the overhead of parsing

http://www.codeproject.com/KB/XML/VTD-XML-indexing.aspx


similar to another answer, you can use xpath similar like selectNodes("//[@attribute='my-target-attribute']"). // will search nodes in all level depths.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜