Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read XElement from XmlReader

I'm playing around with parsing an XMPP XML stream. The tricky thing about the XML stream is that the start tag does not get closed until the end of the session, i.e. a complete DOM is never received.

<stream:stream>
    <features>
       <starttls />
    </features>
    ....
    network session persists for arbitrary time
    ....
 </stream:stream>

I need to read the XML elements from the stream without caring that the root element has not been closed.

Ideally this would work but it doesn't and I'm assuming it's because the reader is waiting for the root element to be closed.

XElement someElement = XNode.ReadFrom(xmlReader) as XElement;

The code below (which I borrowed from Jacob Reimers) does work but I'm hoping there is a more efficient way that doesn't involve creating a new XmlReader and doing the string parsing.

 XmlReader stanzaReader = xmlReader.ReadSubtree();
 stanzaReader.MoveToContent();
 string outerStanza = stanzaReader.ReadOuterXml();
 stanzaReader.Close();
 XElement someElement = XElement.Parse(outerStanza);
like image 444
sipsorcery Avatar asked Nov 15 '10 12:11

sipsorcery


1 Answers

You shouldn't need to work with the strings; you should be able to use XElement.Load on the subtree:

XElement someElement;
using(XmlReader stanzaReader = xmlReader.ReadSubtree()) {
    someElement = XElement.Load(stanzaReader);
}

And note that this isn't really a "new" xml-reader - it is heavily tied to the outer reader (but constrained to a set of nodes).

like image 102
Marc Gravell Avatar answered Nov 11 '22 11:11

Marc Gravell