Lettura di XML utilizzando XPathDocument utilizzando NetworkStream
-
02-01-2020 - |
Domanda
Aspetti APPLICAZIONE:
XPathDocument xPathDocument = new XPathDocument(networkStream);
.
Penso che questo sia dovuto a XPathDocument sta ancora aspettando i dati, ma come impedirlo?
Soluzione
A causa del server non ha chiuso la connessione dopo aver inviato l'intero XML (collegamento restante aperto per la comunicazione futura) XPathDocument attende ancora i dati.Il server non fornisce altri dati per determinare se il trasferimento XML è completato.Tuttavia è possibile verificare che l'intera XML sia ricevuta dal finale del tag root.XPathDocument non cerca il finale del tag root, quindi questa soluzione è un po 'complicata, ma funziona.Sto leggendo il flusso utilizzando XMLReader e riproducono XML da XMLWriter che scrive in StringWriter.All'output della stringa di estremità da StringWriter è suppletato a StringReader, che viene letto da XMLReader.E finnaly, XPathDocument legge i dati da questo XMLReader.Ecco il codice di esempio:
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())));
.
Big ringraziamento per Elgonzo Chi mi ha indicato a questo.