Skip to content

XmlSerializer requires next tag after EndElement to be present in Stream #47371

Closed

Description

@slavanap

Description

XmlSerializer by default requires next tag after EndElement to be present in the Stream to fully deserialize a message. This makes XmlSerializer unapplicable to deserialize directly from NetworkStream.

Configuration

.NET 3.1 or 5; x64

Other information

Demo project:
msg2 is expected to be read successfully because it was fully written.

using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Xml;
using System.Xml.Serialization;

namespace ConsoleApp1 {

    [XmlType(AnonymousType = true)]
    [XmlRoot(ElementName = "msg")]
    public class MessageRoot {
        [XmlAttribute("code")]
        public string Code { get; set; }
        public override string ToString() => $"msg(code: {Code})";
    }

    class Program {
        const int TestPort = 40001;

        static TcpListener _listener;
        static void WriterThread() {
            // dummy writer: write message and block indefinitely
            using var client = _listener.AcceptTcpClient();
            var stream = new StreamMonitor(client.GetStream(), "SERVER");
            TextWriter writer = new StreamWriter(stream, Encoding.ASCII);
            writer.Write(@"<msg code=""1""></msg><msg code=""2""></msg>");
            writer.Flush();
            Thread.Sleep(TimeSpan.FromHours(1));
        }

        static void Main() {
            _listener = new TcpListener(IPAddress.Loopback, TestPort);
            _listener.Start(1);
            var writerThread = new Thread(WriterThread);
            writerThread.Start();

            // this thread will read
            var client = new TcpClient(IPAddress.Loopback.ToString(), TestPort);
            var stream = new StreamMonitor(client.GetStream(), "CLIENT");

            var reader = XmlReader.Create(stream, new XmlReaderSettings { ConformanceLevel = ConformanceLevel.Fragment });
            var serializer = new XmlSerializer(typeof(MessageRoot), string.Empty);

            var msg1 = serializer.Deserialize(reader);
            Console.WriteLine($"We've read message: {msg1}");
            var msg2 = serializer.Deserialize(reader);     // <<< Hangs here.
            Console.WriteLine($"We've read message: {msg2}");

            Console.WriteLine("Success!");
        }
    }

    #region Utility
    class StreamMonitor : Stream {
        readonly Stream _origin;
        readonly string _name;
        public StreamMonitor(Stream origin, string name) {
            _origin = origin;
            _name = name;
        }

        public override bool CanRead => _origin.CanRead;
        public override bool CanSeek => _origin.CanSeek;
        public override bool CanWrite => _origin.CanWrite;
        public override long Length => _origin.Length;
        public override long Position { get => _origin.Position; set => _origin.Position = value; }
        public override void Flush() => _origin.Flush();
        public override long Seek(long offset, SeekOrigin origin) => _origin.Seek(offset, origin);
        public override void SetLength(long value) => _origin.SetLength(value);

        public override int Read(byte[] buffer, int offset, int count) {
            Console.WriteLine($"[{_name} tries to read]");
            var ret = _origin.Read(buffer, offset, count);
            Console.WriteLine($"[{_name} reads {ret} bytes] {new string(Encoding.UTF8.GetChars(buffer, offset, ret))}");
            return ret;
        }

        public override void Write(byte[] buffer, int offset, int count) {
            Console.WriteLine($"[{_name} writes {count} bytes] {new string(Encoding.UTF8.GetChars(buffer, offset, count))}");
            _origin.Write(buffer, offset, count);
        }
    }
    #endregion

}

Area: src/libraries/System.Private.Xml/src/System/Xml/Serialization

Activity

  1. ghost added
    untriaged
    on Jan 23, 2021
  2. slavanap commented on Jan 23, 2021

    @slavanap
    Author

    Same issue - #1029
    But here I've added the sample.

    I have a workaround to share but it involves hacking by redefining XmlTextReader.ReadEndElement to postpone the call for 1st level tag until next message has to be deserialized. XmlTextReader tries to look ahead in the stream causing the hang (please see the provided sample in top message). Printing stack trace @ StreamMonitor.Read entry can make it even more obvious about what's going on.

  3. slavanap commented on Jan 23, 2021

    @slavanap
    Author

    Here's double read just to read end element:
    First - inside MoveToContent function, second - explicit:
    https://source.dot.net/#System.Private.Xml/System/Xml/Core/XmlReader.cs,989

    Simple removal of second Read will certainly violate Xml grammar parsing rules.

  4. removed
    untriaged
    on Feb 11, 2021
  5. HongGit commented on Feb 11, 2021

    @HongGit
    Contributor

    @Benjie-Liu can you please see if you could repro this issue?

  6. added
    Priority:3
    on Jun 21, 2021
  7. added this to the Future milestone on Jul 29, 2021
  8. modified the milestones: Future, 10.0.0 on Jul 31, 2025
  9. modified the milestones: 10.0.0, 11.0.0 on Sep 22, 2025
  10. added
    in-pr
    on Apr 10, 2026
  11. added a commit that references this issue on Apr 30, 2026
    4f111f8
  12. slavanap commented on Apr 30, 2026

    @slavanap
    Author

    @StephenMolloy if it's fixed, this issue may be closed, too.
    #1029

  13. StephenMolloy commented on Apr 30, 2026

    @StephenMolloy
    Contributor

    @StephenMolloy if it's fixed, this issue may be closed, too. #1029

    I wouldn't close that issue. The PR for this is a workaround that we are using in XmlSerializer. But it does not fix the root issue - #1029. That issue should still remain open imho.

  14. locked and limited conversation to collaborators on May 31, 2026
  15. added a commit that references this issue on Jul 15, 2026
    f16ac77
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

Priority:3area-Serializationin-pr

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions