简体   繁体   中英

How do I read a complete XML Element with its children while getting data from NetworkStream?

The code I have until now looks like this.

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

My XML looks like follows.

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

As soon as I hit the XML element <a> I would like to read it to the end (until I hit </a> ) and then fire an event with the whole element and its children.

How do I do it? Is there some mechanism in place that lets me read the stream like that (wait until the end of an element) and then continues with other XML parts?

Well that's probably doable with ReadInnerXmlAsync .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM