0

When i try read my xml file it seems to reads it twice and im unsure on how to fix such an error. I thought i can have some sort of loop but im still lost. Any help would be appreciated ty. - It writes the xml file correctly but the duplicate occurs when it reads it.

String workingDir = Directory.GetCurrentDirectory();
XmlTextReader textReader = new XmlTextReader(workingDir + @"\xmldoc.xml");

Console.WriteLine("BaseURI:" + textReader.BaseURI);
textReader.Read();

while (textReader.Read())
{
    if (textReader.Name == "test")
    {

        textReader.Read();
        XmlNodeType nType = textReader.NodeType;

        if (nType == XmlNodeType.Text)
        {
            //   label.Text = textReader.Value.ToString();
            Label l = new Label();
            System.Drawing.Point l1 = new System.Drawing.Point(15, 13 + a);
            l.Location = l1;
            l.Text = textReader.Value.ToString();

            a += 20;
        }
4

2 回答 2

0

I have no idea what you are REALLY trying to do, and no visibility of you XML, but here is roughly how I would do it.

Notes:

  1. I'm using an XmlReader <- Better IMHO (base class, so there's less waffle)
  2. I'm using "reader.Value" without the ToString() as it's already a string type.
  3. I changed it to be a switch as I think they are cleaner, but there are A LOT of XmlNodeTypes out there and you don't want to have to if/else to much!!!

Code:

        XmlReader reader = XmlReader.Create("books.xml");
        while (reader.Read())
        {
            switch (reader.NodeType)
            {
                case XmlNodeType.Element: // The node is an element.
                    //DO NOTHING
                    break;
                case XmlNodeType.Text: //Display the text in each element.
                    //label.Text = reader.Value;
                    Label l = new Label();
                    System.Drawing.Point l1 = new System.Drawing.Point(15, 13 + a);
                    l.Location = l1;
                    l.Text = reader.Value;
                    a += 20;
                    break;
                case XmlNodeType.EndElement: //Display the end of the element.
                    //DO NOTHING
                    break;
            }
        }
于 2012-06-02T20:06:31.993 回答
0

What makes you think some entries are read twice? If it is the case, also check if this method is not called twice (shift + F12 in Visual Studio to find usage). Also, it seems that the piece of code you joined here is not complete (no declaration of variable 'a'). Do you have some code executed under the if (textReader.Name == "test") that would do the same operations?

于 2012-06-02T21:29:20.083 回答