【问题标题】:How do I read a complete XML Element with its children while getting data from NetworkStream?从 NetworkStream 获取数据时,如何读取完整的 XML 元素及其子元素?
【发布时间】:2013-08-14 21:39:19
【问题描述】:

到目前为止,我的代码如下所示。

using (XmlReader r = XmlReader.Create(stream, new XmlReaderSettings() { Async = true }))
{                    
    while (await r.ReadAsync())
    {
        switch (r.NodeType) {
            case XmlNodeType.Element:
                if (r.IsEmptyElement) // no attributes
                {
                    OnReceive("<" + r.Name + " />");
                }
                else // has attributes
                {
                    OnReceive("<" + r.Name + ">");
                    while (r.MoveToNextAttribute())
                    {
                        OnReceive(r.Name + " -> " + r.Value);
                    }
                }                                
                break;
        }
    }
}

我的 XML 如下所示。

<?xml version='1.0' encoding='UTF-8'?>
<start>
    <a>
        <b></b>
        <c>
            <d>TEXT01</d>
            <d>TEXT01</d>
            <d>TEXT01</d>
            <d>TEXT01</d>
        </c>
        <e>
            <f>TEST01</f>
        </e>
        <g/>
        <h/>
    </a>
...

当我点击 XML 元素 &lt;a&gt; 时,我想将它读到最后(直到我点击 &lt;/a&gt;),然后用整个元素及其子元素触发一个事件。

我该怎么做?是否有某种机制可以让我像这样读取流(等到元素结束)然后继续处理其他 XML 部分?

【问题讨论】:

标签: c# xml-parsing async-await c#-5.0 networkstream


【解决方案1】:

这对ReadInnerXmlAsync 来说可能是可行的。

switch (r.NodeType) {
                            case XmlNodeType.Element:
                                if (r.Name.Equals("a"))
                                {
                                    string x = await r.ReadInnerXmlAsync();
                                    OnReceive(x);
                                }                               
                                break;
                        }

【讨论】:

  • 可能吗?你是说你甚至没有尝试过?
  • 我做到了。但是我遇到了stackoverflow.com/questions/18231945/… 中描述的其他问题。这就是为什么我写:“可能”。现在我知道:这“可能”不是要走的路。
猜你喜欢
  • 1970-01-01
  • 2013-08-24
  • 2019-05-21
  • 1970-01-01
  • 1970-01-01
  • 2018-11-30
  • 2021-05-03
  • 2013-08-28
  • 1970-01-01
相关资源
最近更新 更多