XmlReader skips elements

前端 未结 1 434
旧时难觅i
旧时难觅i 2020-12-11 20:48

I have the following code to stream from a large XML file. However, some elements are skipped. Any reason for this?

public sta         


        
相关标签:
1条回答
  • 2020-12-11 21:15

    XNode.ReadFrom is advancing your reader to the next Campaign open tag (if there is no whitespace between them) then reader.Read will advance to the inner text of that tag. You need to skip the reader.Read after a XNode.ReadFrom like this.

    public static IEnumerable<XElement> StreamItem(string uri)
    {
        using (var reader = XmlReader.Create(uri))
        {
            XElement campaign = null;
    
            reader.MoveToContent();
    
            // Loop through <Campaign /> elements
            reader.Read();
            while (!reader.EOF)
            {
                if (reader.NodeType == XmlNodeType.Element && reader.Name == "Campaign")
                {
                    campaign = XNode.ReadFrom(reader) as XElement;
                    yield return campaign;
                }
                else
                {
                    reader.Read();
                }
            }
        }
    }
    

    Note that if you have Campaign nodes nested in other Campaign nodes those will end up as part of the parent node and not be pulled out as separate nodes.

    0 讨论(0)
提交回复
热议问题