CodexBloom - Programming Q&A Platform

XDocument.Load() throwing XmlException on valid XML string - Unexpected end of file when loading

👀 Views: 118 💬 Answers: 1 📅 Created: 2025-06-23
xml xdocument c# C#

I'm testing a new approach and Quick question that's been bugging me - I've looked through the documentation and I'm still confused about I'm trying to load an XML string into an `XDocument` object in C#... The XML string I'm using seems valid; however, I'm working with an `XmlException` that says "Unexpected end of file while parsing." The XML looks like this: ```xml <customers> <customer id="1"> <name>John Doe</name> <email>john.doe@example.com</email> </customer> </customers> ``` I'm loading it using the following code: ```csharp using System.Xml.Linq; string xmlString = "<customers><customer id=\"1\"><name>John Doe</name><email>john.doe@example.com</email></customer></customers>"; XDocument doc = XDocument.Load(new StringReader(xmlString)); ``` I have confirmed that the `xmlString` is not truncated, and I have checked for any invisible characters or encoding issues. Using `XElement.Parse(xmlString)` instead works fine, but I need to stick with `XDocument.Load()` for consistency across my codebase. I’m using .NET 5.0, and I’ve also verified that the necessary namespaces are included. From my understanding, `XDocument.Load()` should handle the XML string correctly. Is there something specific about how `XDocument.Load()` reads the input that I might be overlooking? Any insights would be greatly appreciated! This is part of a larger API I'm building. What's the best practice here? Is there a simpler solution I'm overlooking? My team is using C# for this service.