Read XElement from XmlReader

2020-02-12 04:58发布

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

1条回答
虎瘦雄心在
2楼-- · 2020-02-12 05:04

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

查看更多
登录 后发表回答