LINQtoXMLGetXElementValue我在从LINQtoXML查询返回一些值时遇到问题。我从SOAPWeb服务获取XML并通过它并将其解析为XDocument进行查询XML:0SuccesstrueGardenWasteCollectionServiceRR3GDNTueFort2Tuesday01/04/2014RecyclingCollectionServiceRR8RECTueFort2Tuesday01/04/2014RefuseCollection服务RR8REFTueFort1周二08/04/2014花园垃圾收集服务RR3GDNTueFort2周二15/04/2014回收服务RR8RECTueFort2周二15/04/2014垃圾收集服务RR8REFTueFort1周二22/04/2014CS代码:使用(varreader=newStreamReader(response.GetResponseStream())){stringxmlString=reader.ReadToEnd();XDocumentxmlDoc=XDocument.Parse(xmlString);varcollections=(frompinxmlDoc.Descendants()wherep.Name.LocalName=="Collection"selectp);vartest=xmlDoc.Descendants("Collection").Select(x=>new{day=x.Element("Day").Value,date=x.Element("Date").Value});Debug.WriteLine("停在这里");vartest2=(来自xmlDoc.Descendants()中的p,其中p.Name。LocalName=="Collection"selectnew{day=p.Element("Day").Value,date=p.Element("Date").Value});上面的collectionvar给出了一个节点列表,但是test和test2vars没有让我的子元素得到任何帮助!这是让您头疼的问题:xmlns="http://webservices.whitespacews.com/"这是为元素及其后代设置默认名称空间-因此您需要查找本地名称为Collections的元素,并且命名空间。其他元素也是如此。幸运的是,LINQtoXML可以让您轻松实现:XNamespacens="http://webservices.whitespacews.com/";...vartest=xmlDoc.Descendants(ns+"Collection").Select(x=>new{day=x.Element(ns+"Day").Value,date=x.Element(ns+"Date")。价值});我怀疑您的test2集合将包含该元素,但由于它找不到Day和Date元素,因此获取Value属性将导致NullReferenceException。另请注意,您不需要创建自己的阅读器等。我会把你的代码写成:以上是C#学习教程:LINQtoXML获取XElement值共享的全部内容。如果对大家有用,需要详细了解C#学习教程,希望大家多加关注——XNamespacens="http://webservices.whitespacews.com/";X文档文档;使用(varstream=response.GetResponseStream()){doc=XDocument.Load(stream);}varquery=xmlDoc.Descendants(ns+"Collection").Select(x=>new{Day=x.Element(ns+"Day").Value,Date=x.Element(ns+"Date").价值});本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:
