static void Main(string[] args)
        {            
            FileStream myFile = new FileStream("..\\..\\test2.xml", FileMode.Open);
            XmlTextReader myReader = new XmlTextReader(myFile);
            myReader.WhitespaceHandling = WhitespaceHandling.Significant;
            Stack myStack = new Stack();
            while(myReader.Read())
                switch (myReader.NodeType)
                {
                    case XmlNodeType.Element:
                        if (myReader.Name == "billingAddress")
                            //peek at the top of the stack - is it billingAddress?
                            if (myStack.Peek().ToString() == "customer")
                                //it is - write the value
                                Console.Write(myReader.ReadElementString() + "\n");
                        if (!myReader.IsEmptyElement)
                            //we're inside this one - push it onto the stack
                            myStack.Push(myReader.Name);
                        break;
                    case XmlNodeType.EndElement:
                        //we need to pop this one off the stack
                        myStack.Pop();
                        break;
                    default:
                        break;
                }
            myReader.Close();
            myFile.Close();
        }这段程序总是执行到最后一步时出错,就是在读取</customer>节点时,不知道为什么,说堆栈为空,不能在出栈了?下面是test2.xml:
<?xml version="1.0" encoding="utf-8" ?>
<customer>
<shippingAddress>
<address>101 First Address</address>
<city>Bluesville</city>
<state>LA</state>
<postalCode>12345</postalCode>
</shippingAddress>
<billingAddress>
<address>202 Second Street</address>
<city>Redsville</city>
<state>NM</state>
<postalCode>23456</postalCode>
</billingAddress>
</customer>

解决方案 »

  1.   

    while(myReader.Read())
    改为while(!myReader.EOF && myReader.Read())
    试一下
      

  2.   

    你的目的想干吗?我感觉你switch条件有些不对头,myReader.NodeType
      

  3.   

    Console.Write(myReader.ReadElementString() + "\n"); 有问题,你把这句话去掉,执行就正常了,最好不要用xmltextreader
      

  4.   

    用IE打開XML文件,看看你的XML可以打開嗎?
      

  5.   

    增加判断
    //we need to pop this one off the stack
    if(myStack.Count > 0)
    {
    myStack.Pop();
    }
      

  6.   

    楼上的兄弟,你那样虽然避免了抛出异常,但是可能已经违背了楼主先前的意愿了吧,我觉得是用XmlTestReader出的问题,最好不要用那个类。