程序挂起:
XPathDocument xPathDocument = new XPathDocument(networkStream);
我认为这是由于XPathDocument仍在等待数据,但如何防止它?
由于服务器在发送整个XML后没有关闭连接(连接仍然打开以供将来通信)XPathDocument仍然等待数据。服务器不提供任何其他数据来确定XML传输是否完成。但是,可以检查根标记结尾是否接收到整个XML。XPathDocument不查找根标记结尾,所以这个解决方案有点棘手,但可以工作。我使用XmlReader读取流,并通过XmlWriter在StringWriter中写入XML。最后,StringWriter的字符串输出提供给StringReader,由XmlReader读取。最后,XPathDocument从这个XmlReader读取数据。下面是示例代码:
XmlReader xmlReader = XmlReader.Create(networkStream);
StringWriter stringWriter = new StringWriter();
XmlWriter xmlReadBuffer = XmlWriter.Create(stringWriter);
while (xmlReader.Read())
{
switch (xmlReader.NodeType)
{
case XmlNodeType.XmlDeclaration:
xmlReadBuffer.WriteStartDocument();
break;
case XmlNodeType.Element:
xmlReadBuffer.WriteStartElement(xmlReader.Name);
if (xmlReader.HasAttributes)
xmlReadBuffer.WriteAttributes(xmlReader, false);
if (xmlReader.IsEmptyElement)
goto case XmlNodeType.EndElement;
break;
case XmlNodeType.EndElement:
if (xmlReader.Depth == 0)
{
xmlReadBuffer.WriteEndElement();
xmlReadBuffer.WriteEndDocument();
goto EndXml;
}
xmlReadBuffer.WriteEndElement();
break;
case XmlNodeType.Text:
xmlReadBuffer.WriteString(xmlReader.Value);
break;
default:
break;
}
}
EndXml:
xmlReadBuffer.Flush();
XPathDocument xPathDocument = new XPathDocument(XmlReader.Create(new StringReader(stringWriter.ToString())));
非常感谢elgonzo给我指出这一点