如何用MSXML遍历XML文档的所有节点?
我现在有如下C#代码,想遍历book.xml的所有节点,包括元素、属性及文本等。可是总出现“传递给此方法的表达式应产生NodeSet”的异常,我换了其它的XPath表达式,只要是返回结点集的都出错。请高手指点。PathDocument doc2 = new XPathDocument("book.xml");
XPathNavigator nav = doc2.CreateNavigator();
try
{
XPathExpression expr2 = nav.Compile("//"); // Returns a nodeset.
if (expr2.ReturnType == System.Xml.XPath.XPathResultType.NodeSet)
{
XPathNodeIterator i = nav.Select(expr2);
while (i.MoveNext())
{
Console.WriteLine(i.Current.ToString());
}
}
}
catch(Exception ex)
{
string msg = ex.Message;
} --------------------编程问答-------------------- 如果是遍历,用xmlreader更合适一点 --------------------编程问答-------------------- 能不能说得具体点该怎么用,我是个新手,谢谢! --------------------编程问答-------------------- protected void Page_Load(object sender, EventArgs e)
{
XmlDocument xml = new XmlDocument();
xml.Load(Request.PhysicalApplicationPath + "xx.xml");
FindNode(xml.ChildNodes);
}
private void FindNode(XmlNodeList nodelist)
{
for (int i = 0; i < nodelist.Count; i++)
{
if (nodelist[i].HasChildNodes)
{
FindNode(nodelist[i].ChildNodes);
}
Response.Write(nodelist[i].Name + "<br>");
}
} --------------------编程问答--------------------
XmlReader reader = XmlTextReader.Create("***.xml");
Console.WriteLine("Begin read xml file:");
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
Console.WriteLine("<{0}>", reader.Name);
if (reader.AttributeCount > 0)
{
//自己加循环吧,懒得改代码了
Console.WriteLine(reader.GetAttribute(0));
}
break;
case XmlNodeType.Text:
Console.WriteLine(reader.Value);
break;
case XmlNodeType.CDATA:
break;
case XmlNodeType.ProcessingInstruction:
Console.WriteLine("<?{0} {1}?>", reader.Name, reader.Value);
break;
case XmlNodeType.Comment:
Console.WriteLine("<!--{0}-->", reader.Value);
break;
case XmlNodeType.XmlDeclaration:
//Console.WriteLine("<?xml version='1.0'?>");
break;
case XmlNodeType.Document:
break;
case XmlNodeType.DocumentType:
Console.WriteLine("<!DOCTYPE {0} [{1}]", reader.Name, reader.Value);
break;
case XmlNodeType.EntityReference:
Console.WriteLine(reader.Name);
break;
case XmlNodeType.EndElement:
Console.WriteLine("</{0}>", reader.Name);
break;
}
}
补充:.NET技术 , C#