从 XmlReader 读取 XElement

发布于 2024-10-02 11:39:55 字数 893 浏览 2 评论 0原文

我正在尝试解析 XMPP XML 流。 XML 流的棘手之处在于,直到会话结束时开始标记才会关闭,即永远不会收到完整的 DOM。

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

我需要从流中读取 XML 元素,而不关心根元素是否已关闭。

理想情况下,这是可行的,但事实并非如此,我假设这是因为读者正在等待根元素关闭。

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

下面的代码(我借自 Jacob Reimers)确实有效,但我希望有一种更有效的方法,不需要创建新的 XmlReader 并进行字符串解析。

 XmlReader stanzaReader = xmlReader.ReadSubtree();
 stanzaReader.MoveToContent();
 string outerStanza = stanzaReader.ReadOuterXml();
 stanzaReader.Close();
 XElement someElement = XElement.Parse(outerStanza);

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

你又不是我 2024-10-09 11:39:55

你不需要使用弦乐;您应该能够使用XElement.Load< /a> 在子树上:

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

请注意,这并不是真正的“新”xml 读取器 - 它与外部读取器紧密相关(但仅限于一组节点)。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文