Home >Backend Development >C++ >How to Access XML Attributes Using C#'s XmlDocument?

How to Access XML Attributes Using C#'s XmlDocument?

Linda Hamilton
Linda HamiltonOriginal
2025-01-06 09:25:40527browse

How to Access XML Attributes Using C#'s XmlDocument?

Accessing XML Attributes with XmlDocument

Reading XML attributes using C#'s XmlDocument can be achieved with a straightforward approach. 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>

To retrieve the attributes SuperNumber and SuperString, you can utilize the following code:

// Load the XML document
XmlDocument doc = new XmlDocument();
doc.Load("myConfig.xml");

// Get the specified element by its tag name
XmlNodeList elemList = doc.GetElementsByTagName("MyConfiguration");

// Iterate through the matching elements
for (int i = 0; i < elemList.Count; i++)
{
    // Access the attribute value
    string attrVal = elemList[i].Attributes["SuperString"].Value;
}

This code snippet uses the GetElementsByTagName method to find the MyConfiguration element. It then iterates through the resulting list and accesses the "SuperString" attribute using the Attributes property. The Value property of the attribute object provides the actual attribute value.

By utilizing this approach, you can easily read and process XML attributes using the XmlDocument class in C#.

The above is the detailed content of How to Access XML Attributes Using C#'s XmlDocument?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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