XmlNodeReader.Prefix
PropertyGets the namespace prefix of the current node.
public string Prefix { get; }
This property returns the namespace prefix of the current node. For example, if the current node is <ns:element xmlns:ns="urn:example" />
, and the current node is the element node, this property returns "ns"
.
If the node does not have a prefix (e.g., it's a default namespace declaration or has no namespace), this property returns an empty string (String.Empty
).
The value returned by this property is case-sensitive, conforming to the XML specification.
For attribute nodes, this property returns the prefix of the attribute name. For element nodes, it returns the prefix of the element name.
Type | Description |
---|---|
string |
The namespace prefix of the current node. Returns String.Empty if the node does not have a prefix. |
The following example demonstrates how to use the Prefix
property.
using System;
using System.Xml;
public class Example
{
public static void Main(string[] args)
{
string xmlString = @"
<root xmlns:data=""http://example.com/data"">
<data:item id=""1"">Sample Item</data:item>
<anotherItem>Another Item</anotherItem>
</root>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlString);
XmlNodeReader reader = new XmlNodeReader(doc.DocumentElement);
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
Console.WriteLine($"Element Name: {reader.Name}");
Console.WriteLine($" Namespace URI: {reader.NamespaceURI}");
Console.WriteLine($" Local Name: {reader.LocalName}");
Console.WriteLine($" Prefix: {reader.Prefix}");
if (reader.HasAttributes)
{
while (reader.MoveToNextAttribute())
{
Console.WriteLine($" Attribute: {reader.Name}");
Console.WriteLine($" Attribute Prefix: {reader.Prefix}");
Console.WriteLine($" Attribute Value: {reader.Value}");
}
reader.MoveToElement(); // Move back to the element node
}
Console.WriteLine();
}
}
reader.Close();
}
}
Element Name: root
Namespace URI:
Local Name: root
Prefix:
Element Name: data:item
Namespace URI: http://example.com/data
Local Name: item
Prefix: data
Attribute: data:id
Attribute Prefix: data
Attribute Value: 1
Attribute: xmlns:data
Attribute Prefix: xmlns
Attribute Value: http://example.com/data
Element Name: anotherItem
Namespace URI:
Local Name: anotherItem
Prefix: