5.4 Find Specific Elements by Name


5.4 Find Specific Elements by Name

Problem

You need to retrieve a specific node from an XmlDocument , and you know its name but not its position.

Solution

Use the XmlDocument.GetElementsByTagName method, which searches an entire document and returns a System.Xml.XmlNodeList containing any matches.

Discussion

The XmlDocument class provides a convenient GetElementsByTagName method that searches an entire document for nodes that have the indicated element name. It returns the results as a collection of XmlNode objects.

This code demonstrates how you could use GetElementsByTagName to calculate the total price of items in a catalog by retrieving all elements with the name " productPrice ":

 using System; using System.Xml; public class FindNodesByName {     private static void Main() {         // Load the document.         XmlDocument doc = new XmlDocument();         doc.Load("ProductCatalog.xml");         // Retrieve all prices.         XmlNodeList prices = doc.GetElementsByTagName("productPrice");         decimal totalPrice = 0;         foreach (XmlNode price in prices) {             // Get the inner text of each matching element.             totalPrice += Decimal.Parse(price.ChildNodes[0].Value);         }         Console.WriteLine("Total catalog value: " + totalPrice.ToString());         Console.ReadLine();     } } 

You can also search portions of an XML document by using the XmlElement.GetElementsByTagName method. It searches all the descendant nodes looking for matches. To use this method, first retrieve an XmlNode that corresponds to an element. Then cast this object to an XmlElement . The following example demonstrates how to find the price node under the first product element.

 // Retrieve a reference to the first product. XmlNode product = doc.GetElementsByTagName("products")[0]; // Find the price under this product. XmlNode price = ((XmlElement)product).GetElementsByTagName("productPrice")[0]; Console.WriteLine("Price is " + price.InnerText); 

If your elements include an attribute of type ID , you can also use a method called GetElementById to retrieve an element that has a matching ID value.




C# Programmer[ap]s Cookbook
C# Programmer[ap]s Cookbook
ISBN: 735619301
EAN: N/A
Year: 2006
Pages: 266

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net