XmlNodeReader.ReadElementContentAsString Method

Syntax

public string ReadElementContentAsString ()

Parameters

This method has no parameters.

Return Value

The content of the element as a string. This can include the text of child elements, CDATA sections, and entity references.

Remarks

This method reads the content of the current element as a string. If the element has attributes, they are ignored.

The content is read until the end of the element is encountered. This includes text nodes, CDATA sections, and entity references. Whitespace characters are preserved.

If the current node is not an element node, an XmlException is thrown.

If the element is empty (e.g., <element/> or <element></element>), an empty string is returned.

Note: This method can be performance intensive for large elements as it reads the entire content into a single string. Consider using other methods like ReadElementContentAs(Type) or streaming the content if memory usage is a concern.

Exceptions

Example

The following example reads the content of an element as a string.


using System;
using System.Xml;

public class Example
{
    public static void Main(string[] args)
    {
        string xmlString = @"<book genre=""fiction"" isbn=""12345"">
                                 <title>The Hitchhiker's Guide to the Galaxy</title>
                                 <author>Douglas Adams</author>
                                 <description><![CDATA[A comedic science fiction series.]]></description>
                             </book>";

        using (XmlReader reader = XmlReader.Create(new System.IO.StringReader(xmlString)))
        {
            while (reader.Read())
            {
                if (reader.IsStartElement())
                {
                    if (reader.Name == "book")
                    {
                        // Move to the content of the book element
                        reader.Read();
                        if (reader.NodeType == XmlNodeType.Text)
                        {
                            Console.WriteLine("Book Content: " + reader.ReadElementContentAsString());
                        }
                        else
                        {
                            // Handle cases where content might be mixed with other nodes
                            // For this simple example, we assume direct text content
                            Console.WriteLine("Unexpected node type: " + reader.NodeType);
                        }
                    }
                }
            }
        }
    }
}
            

Output:


Book Content: The Hitchhiker's Guide to the GalaxyDouglas AdamsA comedic science fiction series.
            
Note: The example above demonstrates reading the *combined* content of child elements and CDATA sections within the 'book' element. If you need to read specific child element content, you would navigate accordingly.

See Also