问题描述
namespaceConsoleApplication1{classProgram{staticvoidMain(string[]args){try{XmlDocumentxmdoc=newXmlDocument();xmdoc.Load("H:\ConsoleApplication1\ConsoleApplication1\test.xml");intnum=xmdoc.DocumentElement.ChildNodes.Count;Console.WriteLine(num);XmlNodenod=xmdoc.SelectSingleNode("employee/sex");stringnotevalue=nod.Value;if(notevalue==null){Console.WriteLine("novalue");}else{Console.WriteLine(notevalue);}}catch(FileNotFoundExceptione){stringexp=e.FileName;Console.WriteLine(exp);}//finally//{//Console.WriteLine("successful");//}}}}为什么nod总是取不到值啊,xmdoc.SelectSingleNode("employee/sex")这个语句有错吗?以下是XML文件<?xmlversion="1.0"encoding="utf-8"?><employee><name>xiaohong</name><sex>female</sex><dept>IT</dept></employee>
解决方案
解决方案二:
xmdoc.SelectSingleNode("/employee/sex")
解决方案三:
xpath命名空间引用了吗不行就用xmdoc.GetElementsByTagName("sex")
解决方案四:
利用一个winform的例子吧。:)我的XML例子的代码如下:<?xmlversion="1.0"encoding="utf-8"?><carlot><car><make>234</make><model>324</model><elapsedMiles>fdsfdsf</elapsedMiles></car><car><make>23434</make><model>3244</model><elapsedMiles>dsfds</elapsedMiles></car></carlot>
我的C#代码:System.IO.StreamReadersr=newSystem.IO.StreamReader(@"cars.xml");System.Xml.XmlTextReaderxr=newSystem.Xml.XmlTextReader(sr);System.Xml.XmlDocumentcarlotDoc=newSystem.Xml.XmlDocument();carlotDoc.Load(xr);label1.Text=carlotDoc.InnerText;label2.Text="FirstChildNode:"+carlotDoc.FirstChild.InnerText;label3.Text="SecondChildNode:"+carlotDoc.FirstChild.NextSibling.InnerText;System.Xml.XmlNodecarlot=carlotDoc.FirstChild.NextSibling;label4.Text="Nowwehaveareferenceto'carlot':"+carlot.InnerText;label5.Text="Firstchlidofcarlot:"+carlot.FirstChild.InnerText;label6.Text="Firstchildoffirstchildofcarlot;"+carlot.FirstChild.FirstChild.InnerText;System.Xml.XmlNodeListcarLotItems=carlotDoc.SelectNodes("carlot/car");System.Xml.XmlNodemake=carLotItems.Item(0).SelectSingleNode("make");label7.Text="make.innertext:"+make.InnerText;
不好意思。里面拖了7个label控件。执行一下,看结果,可以对你作为参考。
解决方案五:
stringnotevalue=nod.InnerText;