.NET API Documentation

XmlReader.ReadValueAsBytes()

public byte[] ReadValueAsBytes()

Description

Reads the current node's value as a byte array. This method can be called on elements, attributes, or text nodes.

When called on an element node, it reads the value of the first child element. If the element has no children or the first child is not a text node, it throws an InvalidOperationException.

When called on an attribute node, it reads the attribute value.

When called on a text node, it reads the text content.

Remarks

This method attempts to decode the value as Base64 if the content is Base64 encoded. If the content is not Base64 encoded but can be interpreted as a byte array, it will be converted accordingly. Otherwise, an exception may be thrown or an empty array returned depending on the context.

It is recommended to use this method only when you expect the node's value to be representable as binary data.

Exceptions

  • InvalidOperationException: If the node type is not an element, attribute, or text node, or if the value cannot be converted to a byte array.
  • XmlException: If there are XML parsing errors.

Example

The following example demonstrates how to use the ReadValueAsBytes method to read Base64 encoded binary data from an XML element.

using System; using System.Xml; public class Example { public static void Main(string[] args) { string xmlString = @@"<root><binaryData>SGVsbG8gV29ybGQh</binaryData></root>"; XmlReader reader = XmlReader.Create(new StringReader(xmlString)); while (reader.Read()) { if (reader.IsStartElement() && reader.Name == "binaryData") { byte[] data = reader.ReadValueAsBytes(); Console.WriteLine("Read binary data: " + BitConverter.ToString(data)); } } reader.Close(); } } // Output: Read binary data: 48-65-6C-6C-6F-20-57-6F-72-6C-64-21