Overview
Reads the text content of the current node and returns it as a string. This method attempts to read all text content within the current node, including character data, ignorable white space, significant white space, and CDATA sections. If the current node is an element, it reads all descendant text nodes.
Assembly: System.Xml.dll
Syntax
Parameters
This method does not take any parameters.
Return Value
The text content of the current node as a string. Returns an empty string if the node has no text content.
Remarks
This method is useful for retrieving the full text content of an element, even if it spans multiple nodes (e.g., mixed content with text and other elements).
If the current node is an attribute, this method returns the attribute's value. If the current node is an element, it reads the text content of the element and any descendant text nodes.
Calling this method repeatedly will consume the node. If the node has already been read, subsequent calls may return an empty string or throw an exception depending on the reader's state.
The method handles XML entities correctly, decoding them into their corresponding characters.
Exceptions
InvalidOperationException: Thrown if the reader is not positioned on a node that has text content (e.g., an element, attribute, or CDATA section).
XmlException: Thrown if the XML is not well-formed.
Example
The following example demonstrates how to use the ReadContentAsString
method to read the text content of an XML element.
<?xml version="1.0" encoding="utf-8"?>
<root>
<message>Hello, <strong>World</strong>!</message>
</root>
using System;
using System.Xml;
public class Example
{
public static void Main(string[] args)
{
string xmlString = @"<?xml version=""1.0"" encoding=""utf-8""?>
<root>
<message>Hello, <strong>World</strong>!</message>
</root>";
using (XmlReader reader = XmlReader.Create(new System.IO.StringReader(xmlString)))
{
while (reader.Read())
{
if (reader.IsStartElement() && reader.Name == "message")
{
// Move to the content of the 'message' element
reader.Read();
// Read the entire content as a string
string content = reader.ReadContentAsString();
Console.WriteLine($"Message Content: {content}"); // Output: Message Content: Hello, World!
// Since ReadContentAsString consumed the content, we can move past it
// to avoid issues in the next iteration. If 'message' had child elements,
// ReadContentAsString would have returned the concatenated text.
// In this simple case, it reads until the end of the element.
}
}
}
}
}