views:

202

answers:

1

I have the following XML that is built up at runtime using an XmlDocument:

<?xml version="1.0" standalone="yes"?>
<NewConfig xmlns="http://tempuri.org/NewConfig.xsd"&gt;
  <SystemReference xmlns="">
    <ID>1</ID>
    <Name>CountryName</Name>
  </SystemReference>
  <ClientList xmlns="">
    <Type>Private</Type>

    <!-- elements omitted... -->

    <VAT>1234567890</VAT>
  </ClientList>
</NewConfig>

I'm saving this XML to a TCP socket with the following code:

TcpClient client = ...
XmlDocument configDocument = ...

using (StreamWriter writer = new StreamWriter(client.GetStream()))
{
  writer.AutoFlush = true;
  configDocument.Save(writer);
  writer.WriteLine();
}

But this causes the XML that is received by the other end of the socket to be truncated - the last 2 elements (</ClientList> and </NewConfig>) are never present.

However, if I use the following code, the XML is sent successfully:

TcpClient client = ...
XmlDocument configDocument = ...

using (StreamWriter writer = new StreamWriter(client.GetStream()))
{
  writer.AutoFlush = true;
  writer.WriteLine(configDocument.OuterXml);
}

My question therefore, is: Does anyone know why XmlDocument.Save() seems to be ignoring the closing elements when writing to the Stream?

+1  A: 

There's nothing wrong with both ways of sending the data. What is wrong is the way you read the XML on the server side. For example using the first method and the following listener, I was able to get the entire XML:

class Program
{
    static void Main(string[] args)
    {
        var listener = new TcpListener(IPAddress.Loopback, 9999);
        listener.Start();
        while (true)
        {
            var client = listener.AcceptTcpClient();
            using (var stream = client.GetStream())
            using (var reader = new StreamReader(stream))
            {
                Console.WriteLine(reader.ReadToEnd());
            }
        }
    }
}
Darin Dimitrov