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>
{
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>
改为while(!myReader.EOF && myReader.Read())
试一下
//we need to pop this one off the stack
if(myStack.Count > 0)
{
myStack.Pop();
}