为什么StreamReader.ReadLine在读取XML方面比XmlTextReader.Read做得更好?

时间:2014-08-28 23:54:58

标签: c# xml streamreader readline xmltextreader

我有这个代码可以从调用Web API应用程序的Winforms应用程序中正常工作(它成功地将XML文件复制到服务器上):

public static string SendXMLFile(string xmlFilepath, string uri, int timeout)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);

    request.KeepAlive = false;
    request.ProtocolVersion = HttpVersion.Version10;
    request.ContentType = "application/xml";
    request.Method = "POST";

    StringBuilder sb = new StringBuilder();
    using (StreamReader sr = new StreamReader(xmlFilepath))
    {
        String line;
        while ((line = sr.ReadLine()) != null)
        {
            sb.AppendLine(line);
        }
        MessageBox.Show(sb.ToString());
        byte[] postBytes = Encoding.UTF8.GetBytes(sb.ToString());

        if (timeout < 0)
        {
            request.ReadWriteTimeout = timeout;
            request.Timeout = timeout;
        }

        request.ContentLength = postBytes.Length;

        try
        {
            Stream requestStream = request.GetRequestStream();

            requestStream.Write(postBytes, 0, postBytes.Length);
            requestStream.Close();

            HttpWebResponse response = null; //<= uncomment for older versions of .NET
            try
            {
                response = (HttpWebResponse)request.GetResponse(); //<= uncomment for older versions of .NET (comment out using)
            }
            finally
            {
                IDisposable disposableResponse = response as IDisposable;
                if (disposableResponse != null) disposableResponse.Dispose();
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
            request.Abort();
            return string.Empty;
        }
    }
}

然而,当试图弄清楚为什么代码尽可能与此工作代码相似时,尝试将xml文件从手持设备发送到同一服务器时不起作用,我尝试使用XmlTextReader(因为建议here(“你没有在这里使用XML类和方法”),在那里我详细介绍了我的艰辛);唯一的区别是:

using (StreamReader sr = new StreamReader(xmlFilepath))
{
    String line;
    while ((line = sr.ReadLine()) != null)
    {
        sb.AppendLine(line);
    }
    MessageBox.Show(sb.ToString());
    byte[] postBytes = Encoding.UTF8.GetBytes(sb.ToString());

...在工作(StreamReader)代码中更改为:

XmlTextReader reader = new XmlTextReader(xmlFilepath);
while (reader.Read())
{
    switch (reader.NodeType)
    {
        case XmlNodeType.Element: // The node is an Element.
            sb.Append("<" + reader.Name);

            while (reader.MoveToNextAttribute()) // Read attributes.
                sb.Append(" " + reader.Name + "='" + reader.Value + "'");
            sb.Append(">");
            sb.Append(">");
            break;
        case XmlNodeType.Text: //Display the text in each element.
            sb.Append(reader.Value);
            break;
        case XmlNodeType.EndElement: //Display end of element.
            sb.Append("</" + reader.Name);
            sb.Append(">");
            break;
    }
}

MessageBox.Show(sb.ToString());
byte[] postBytes = Encoding.UTF8.GetBytes(sb.ToString());

使用StreamReader代码,读取的数据看起来就像在磁盘上一样:

enter image description here

然而,使用XmlTextReader,它就像jambalaya在一群河马中射出的大炮一样混乱:

enter image description here

...并且XmlTextReader版本失败,“远程服务器返回错误:(500)内部服务器错误。

因此,StreamReader.ReadLine可以更好地使用XML文件,而不是XmlTextReader.Read。看起来很奇怪......我在这里做错了吗?

1 个答案:

答案 0 :(得分:2)

默认情况下,XmlTextReader会忽略空格。您将要特别告诉它包含空格并开始处理交换机中的空格。

另请注意,所有XmlReader实现都是一次性的,因此请将它们包装在using中。

XmlReaderSettings settings = new XmlReaderSettings();
settings.IgnoreWhitespace = false;
using(XmlReader reader = XmlReader.Create(xmlFilepath, settings)) {
    while (reader.Read())
    {
        switch (reader.NodeType)
        {
            case XmlNodeType.Element: // The node is an Element.
                sb.Append("<" + reader.Name);

                while (reader.MoveToNextAttribute()) // Read attributes.
                    sb.Append(" " + reader.Name + "='" + reader.Value + "'");
                sb.Append(">");
                sb.Append(">");
                break;
            case XmlNodeType.Text: 
            case XmlNodeType.Whitespace:
                sb.Append(reader.Value);
                break;
            case XmlNodeType.EndElement: //Display end of element.
                sb.Append("</" + reader.Name);
                sb.Append(">");
                break;
        }
    }
}
MessageBox.Show(sb.ToString());
byte[] postBytes = Encoding.UTF8.GetBytes(sb.ToString());