简体   繁体   中英

C# XML Parsing - Searching for specific elements

I'm using an XMLReader in C# .net 4.0 to search through a small snippet of XML. I want to find specific elements in the XML, and I'm using the XMLReader.ReadToFollowing("name") method to find the elements. I do not know the order in the XML document that the elements are; they be in a difference sequence or missing entirely. The order does not matter to me, but I will throw an exception if the element is missing.

The XMLReader is forward only, so if the first element I'm looking for is the last value in the XML document, additional reads will fail.

I was thinking of creating a new XMLReader for each search. I only have a small set of elements to find and the XML isn't huge so I don't think there will be much overhead, but I could be wrong.

Is there a better library to use for searching XML when you do not know the order of the elements? Or is a lack of order in XML a violation of the XML specification?

Specifically, let's say I have some simple XML. A head and 10 Children.

<sometag>
     <element1>data</element1>
     <element2>data</element2>
     .
     .
     .
     <element10>data</element10>
</sometag>

Would it be inefficient to open 5 XMLReaders to find those elements? I could also use the one reader and step through each element, but then I would need to keep track of which elements I've found.

Instead of XMLReader you could use XDocument (linq2xml), do it fast and easy (by Element method):

var doc = XDocument.Load(xmlFilePath);
var element1 = doc.Element(searchItemName);
if (element1 == null) throw ...
...
return ....;

You can call it as many time as you like without reloading xml file.

Try using XPath. It is much faster and isn't sensitive to the order of elements (only the hierarchy).

MSDN Documentation: http://msdn.microsoft.com/en-us/library/ms256086.aspx

Programming with XPath does require a bit of learning. And if your XML specifies a namespace, you'll need to be sure to include that in your XPath query.

您具有.NET 4.0,因此请使用Linq到XML。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM