Home > Backend Development > C++ > How Do I Read XML Attributes Using C#'s XmlDocument?

How Do I Read XML Attributes Using C#'s XmlDocument?

Mary-Kate Olsen
Release: 2025-01-06 09:10:40
Original
259 people have browsed it

How Do I Read XML Attributes Using C#'s XmlDocument?

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>
Copy after login

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;
}
Copy after login

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:

  • SuperNumber: "1"
  • SuperString: "whipcream"

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template