Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
309 views
in Technique[技术] by (71.8m points)

c# - XmlReader skips elements

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

public static IEnumerable<XElement> StreamItem(string uri)
{
    using (var reader = XmlReader.Create(uri))
    {
        XElement campaign = null;

        reader.MoveToContent();

        // Loop through <Campaign /> elements
        while (reader.Read())
        {
            if (reader.NodeType == XmlNodeType.Element && reader.Name == "Campaign")
            {
                campaign = XNode.ReadFrom(reader) as XElement;
                yield return campaign;
            }
        }
    }
}

Update:

The XML file is well-formed and has the following structure.

<CRoot>
    <Campaign CampaignID="136">
        <!-- other nested elements -->
    </Campaign>
    <Campaign CampaignID="137">
        <!-- other nested elements -->
    </Campaign>
    <!-- etc -->
</CRoot>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...