dotnet / dotnet/dotnet-api-docs

XmlReader.MoveToContent Examples Throw Exception Unless XmlReader Has Correct Conformance Level

Open
#9,114 1 comment 0 reactions 0 assignees View on GitHub
area-System.Xml Pri3
Dominant language
C#
Stars
949
Forks
1.7k
Avg merge
3d 27m
Merged PRs (30d)
49

Description

The [XmlReader.MoveToContent Method](https://learn.microsoft.com/dotnet/api/system.xml.xmlreader.movetocontent#examples) page has example code [line: 3465](https://github.com/dotnet/dotnet-api-docs/blob/main/xml/System.Xml/XmlReader.xml#L3465) that can throw the exception `System.Xml.XmlException`.

This can happen when using a reader that has its conformance level set to document *OR* reusing a reader initialized with conformance level set to auto.

The example should demonstrate using a reader with `Settings.ConformanceLevel` set to `ConformanceLevel.Fragment`. The code will then *"handle the following inputs without breaking"*.

This was tested with the following code:

```csharp
XmlReader reader = XmlReader.Create("Test.xml", new()
{
IgnoreProcessingInstructions = true,
IgnoreWhitespace = true,
ConformanceLevel = ConformanceLevel.Fragment,
});

byte[] bytes = Encoding.UTF8.GetBytes(
@"""
123.4
""");

reader = XmlReader.Create(new MemoryStream(bytes));

// Exception thrown here:
if (reader.MoveToContent() == XmlNodeType.Element && reader.Name == "price")
{
var foo = reader.ReadString();
}
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.