开发者

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);


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜