C# XML find first Element descendants -
looking find categoryid
, categoryname
first item
. return no products.
xml looks
<finditemsbykeywordsresponse xmlns="http://..."> <ack>success</ack> <version>1.13.0</version> <timestamp>2016-11-10t17:48:21.321z</timestamp> <searchresult count="1"> <item> <itemid>12354</itemid> <title>abcd#</title> <globalid>ddd</globalid> <primarycategory> <categoryid>**1234**</categoryid> <categoryname>**catg nameee**</categoryname> </primarycategory> </item> </searchresult> <paginationoutput> </paginationoutput> </finditemsbykeywordsresponse>
full xml here
because root element has namespace defined should when searching descendant items specify namespace:
xnamespace ns = @"http://www.ebay.com/marketplace/search/v1/services"; var result = xdocument.load("data.xml") .descendants(ns + "item") .firstordefault()?.element(ns + "primarycategory"); var categoryid = result?.element(ns + "categoryid")?.value; var categoryname = result?.element(ns + "categoryname")?.value;
also can use c# 6.0 null propagation (?:
) retrieve <primarycategory>
in more elegant way. keep in mind if not have <item>
tag or <primarycategory>
tag result equal null
in addition might make more sense try , find first <item>
answers predicate. if case change .firstordefault()
with: .firstordefault(item => item.element("itemid").value == "12345")
example
Comments
Post a Comment