Reading XML Attributes with XmlDocument
Accessing XML attributes using C#'s XmlDocument proves particularly useful when navigating through complex XML structures. Let's delve into an example to illustrate how it's done.
Consider the following XML document:
<?xml version="1.0" encoding="utf-8" ?> <MyConfiguration xmlns="http://tempuri.org/myOwnSchema.xsd" SuperNumber="1" SuperString="whipcream"> <Other stuff /> </MyConfiguration>
Extracting Attributes
To extract attributes from the above XML, you can leverage XmlDocument's GetElementsByTagName() method to retrieve specific elements and then access their Attributes collection to get the attribute values. Here's how:
XmlNodeList elemList = doc.GetElementsByTagName(...); for (int i = 0; i < elemList.Count; i++) { string attrVal = elemList[i].Attributes["SuperString"].Value; }
In this code, elemList represents the collection of elements identified by the specified tag name. By iterating through this collection, you gain access to each element's Attributes collection and, subsequently, the attribute values.
For the given XML example, you would obtain the following results:
The above is the detailed content of How Do I Read XML Attributes Using C#'s XmlDocument?. For more information, please follow other related articles on the PHP Chinese website!