XmlNodeReader.ReadAttributeValue Method
public string ReadAttributeValue()
Summary
Reads the attribute value and returns it as a string.
Returns
- A
string
containing the attribute value.
Remarks
This method is used to retrieve the value of an attribute when the current node is an attribute. It returns the value as a plain string, resolving any entity references.
If the current node is not an attribute, the behavior of this method is undefined, and it may throw an exception or return an unexpected result.
Example
The following example demonstrates how to use the ReadAttributeValue
method to read attribute values from an XML document using XmlNodeReader
.
using System;
using System.Xml;
public class Example
{
public static void Main(string[] args)
{
string xmlString = @"
<root xmlns:myprefix='http://example.com/ns' myattribute='somevalue'>
<element attribute2=""another"">Content</element>
</root>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlString);
XmlNodeReader reader = new XmlNodeReader(doc.DocumentElement);
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Attribute)
{
Console.WriteLine($"Attribute Name: {reader.Name}");
Console.WriteLine($"Attribute Value: {reader.ReadAttributeValue()}");
}
else if (reader.NodeType == XmlNodeType.Element && reader.HasAttributes)
{
Console.WriteLine($"Element: {reader.Name}");
for (int i = 0; i < reader.AttributeCount; i++)
{
reader.MoveToAttribute(i);
Console.WriteLine($" Attribute Name: {reader.Name}");
Console.WriteLine($" Attribute Value: {reader.Value}");
}
reader.MoveToElement(); // Move back to the element node
}
}
}
}