XmlTextReader - reading from a string?
-
All, Just wondering if it is possible to parse XML from a string in memory, as opposed to a file? I'm getting XML data over a TCP/IP connection, and it is read into a string in memory. I could dump the string to a file, then parse the filename to XmlTextReader, but that seems like a waste of resources. Any pointers would be appreciated. Cheers, Andrew
-
All, Just wondering if it is possible to parse XML from a string in memory, as opposed to a file? I'm getting XML data over a TCP/IP connection, and it is read into a string in memory. I could dump the string to a file, then parse the filename to XmlTextReader, but that seems like a waste of resources. Any pointers would be appreciated. Cheers, Andrew
Hi Andrew, there are some solutions: 1st) If you only want an XmlDocument, use the methode LoadXml of the XmlDocument class.
string myXmlContent = @"<GoodSides><Side name='CodeProject'>http://www.codeproject.com</Side></GoodSides>"; XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(myXmlContent);
2nd) Copy the bytes (or strings) to a MemoryStream.byte[] myContent = ...; MemoryStream memStream = new MemoryStream(myContent); XmlTextReader xmlReader = new XmlTextReader(memStream);
orMemoryStream memStream = new MemoryStream(); StreamWriter memWriter = new StreamWriter(memStream); memWriter.Write(@"<GoodSides>"); memWriter.Write(@"<Side name='CodeProject'>http://www.codeproject.com</Side>"); memWriter.Write(@"</GoodSides>"); memStream.Position = 0; // Reset the position XmlTextReader xmlReader = new XmlTextReader(memStream);
3rd) Implement a own class with Stream as BaseClass. This class can read the datas direct from TCP/IP.class MyOwnStream: Stream { // especialy int Read(byte[] buffer, int offset, int count) { ... } }; MyOwnStream myStream = new MyOwnStream(...); XmlTextReader xmlReader = new XmlTextReader(myStream);
4th) Use the SocketStream direct. (If the stream contains only the xml data and no more.)NetworkStream myNetworkStream = new NetworkStream(mySocket); XmlTextReader xmlReader = new XmlTextReader(myStream);
Hope, it helps Niedzi