This method has no parameters.
The content of the element as a string. This can include the text of child elements, CDATA sections, and entity references.
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.
ReadElementContentAs(Type)
or streaming the content if memory usage is a concern.
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.