dotnet / dotnet-api-docs

.NET API reference documentation (.NET 5+, .NET Core, .NET Framework)
https://docs.microsoft.com/dotnet/api/
Other
713 stars 1.56k forks source link

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

Open zacharylayne opened 1 year ago

zacharylayne commented 1 year ago

The XmlReader.MoveToContent Method page has example code line: 3465 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:

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

byte[] bytes = Encoding.UTF8.GetBytes(
    @"""
    <?xml version=""1.0""><!DOCTYPE price SYSTEM
     ""abc""><price>123.4</price>
    """);

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

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

Tagging subscribers to this area: @dotnet/area-system-xml See info in area-owners.md if you want to be subscribed.

Issue Details
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(); } ```
Author: zacharylayne
Assignees: -
Labels: `untriaged`, `Pri3`, `area-System.Xml`
Milestone: -