阅读的XElement从XmlReader的XElement、XmlReader

由网友(余温)分享简介:我与解析XMPP XML流玩耍。关于XML流的棘手的事情是开始标签不会被关闭,直到会议结束,即完整的DOM从未收到。<流:流><功能>< STARTTLS />< /功能>....网络会话持续任意时间....< /流:流>我需要从流读取XML元素,而无需关心根...

我与解析XMPP XML流玩耍。关于XML流的棘手的事情是开始标签不会被关闭,直到会议结束,即完整的DOM从未收到。

 <流:流>
    <功能>
       < STARTTLS />
    < /功能>
    ....
    网络会话持续任意时间
    ....
 < /流:流>
 

我需要从流读取XML元素,而无需关心根元素没有被关闭。

在理想情况下,这将工作,但它不和我猜想这是因为读者正在等待被关闭的根元素。

 的XElement someElement = XNode.ReadFrom(的XMLReader)作为的XElement;
 

下面的code(这是我从Jacob赖默斯)正常工作,但我希望有不涉及创建一个新的XmlReader,做字符串解析一个更有效的方法。

 的XmlReader stanzaReader = xmlReader.ReadSubtree();
 stanzaReader.MoveToContent();
 字符串outerStanza = stanzaReader.ReadOuterXml();
 stanzaReader.Close();
 的XElement someElement = XElement.Parse(outerStanza);
 
使用SimpleXML实现对XML数据的遍历操作

解决方案

您应该不需要与字符串工作;你的应该的能够使用 XElement.Load 的子树:

 的XElement someElement;
使用(XmlReader的stanzaReader = xmlReader.ReadSubtree()){
    someElement = XElement.Load(stanzaReader);
}
 

和注意,这是不是一个真正的新的XML阅读器 - 它在很大程度上依赖于外部读卡器(但限制为一组节点)

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

阅读全文

相关推荐

最新文章