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
387 views
in Technique[技术] by (71.8m points)

c# - XmlReader - problem reading xml file with no newlines

When I use XmlReader to parse an XML file, I get different results depending on whether the XML file is properly formatted (i.e. with newlines) or not.

This is the code I'm using:

XmlReader reader = new XmlTextReader(xmlfile);
reader.MoveToContent();
while (reader.Read())
{
    switch (reader.NodeType)
    {
        case XmlNodeType.Element:
            if (reader.Name == "entry")
            {
                Console.WriteLine(reader.ReadElementContentAsString());
            }
            break;
    }
}

And the XML content I've been using is:

<xport><meta><columns>5</columns><legend><entry>AVERAGE:host:ed402b4d-71e7-4a8d-be29-ab6e54e955c8:memory_total_kib</entry><entry>AVERAGE:host:ed402b4d-71e7-4a8d-be29-ab6e54e955c8:memory_free_kib</entry><entry>AVERAGE:host:ed402b4d-71e7-4a8d-be29-ab6e54e955c8:xapi_memory_usage_kib</entry><entry>AVERAGE:host:ed402b4d-71e7-4a8d-be29-ab6e54e955c8:xapi_free_memory_kib</entry><entry>AVERAGE:host:ed402b4d-71e7-4a8d-be29-ab6e54e955c8:xapi_live_memory_kib</entry></legend></meta></xport>

The code prints out only 3 lines, when it really should be printing 5. I guess I'm missing something, but it doesn't make sense to me that the same code would produce different results on the same XML file when I don't have white-spaces.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

See Why does XmlReader skip every other element if there is no whitespace separator?

You're calling [ReadElementContentAsString], which will consume the element and place the "cursor" just before the next element. You're then calling Read again, which moves the cursor on (e.g. to the text node within the element).

Modified loop (almost exactly like in the other question):

while (!reader.EOF)
{
    if (reader.NodeType == XmlNodeType.Element && reader.Name == "entry")
    {
        Console.WriteLine(reader.ReadElementContentAsString());
    }
    else
    {
        reader.Read();
    }
}

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

...