简体   繁体   中英

LINQ where clause returns null

I'm trying to get values from xml using LINQ. When I add where clause I get null. When I remove the where clause I get items from xml, but there's no property for 'Value'.

This is the xml I'm trying to get BatchId, ResultCode, and SearchId values from.

{<WsSearchReply xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <ExtensionData />
  <BatchId>6787350</BatchId>
  <Hits />
  <ResultCode>NO_HITS</ResultCode>
  <SearchId>67292500</SearchId>
</WsSearchReply>}

This returns 4 items:
IEnumerable<XNode> dps = from el in d.Root.Nodes()
                              select el;

this doesn't return any records:
IEnumerable<XNode> dps = from el in d.Root.Nodes()
                         where el.Equals("<ExtensionData />")
                         select el;

using System.Xml;
using System.Xml.Linq;

string text = Serializer.SerializeObject<CchSearchService.WsSearchReply>(reply, true);

XDocument d = new XDocument();
XElement e = XElement.Parse(text);
d.Add(e);

IEnumerable<XNode> dps = from el in d.Root.Nodes()
//where el.Equals("<ExtensionData />")
 select el;

foreach (XNode el in dps)
{
    string x = el.ToString();
    Console.WriteLine(el);
}

To get the ExtensionData elements you can simply use the following:

IEnumerable<XElement> dps = d.Root.Elements("ExtensionData");

which essentially is a quick way of doing this (you have suggested that you must use lync for this in a comment, the below code is unnecessary)

IEnumerable<XElement> dps = from el in d.Root.Elements() where el.Name.LocalName.Equals("ExtensionData") select el;

For further info, an XElement implements XNode . XNode is the base class and the Nodes enumerable can contain things other than elements such as comments (XComment) and does not have a name. If you use the Elements property you will only return XElement objects. The XElement class contains data relating to an Element eg the Element name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM