在mvc控制器上获取xml单个值

时间:2017-10-29 20:11:12

标签: asp.net-mvc

请检查下面的XML响应。我想从整个X​​ML中获取变量中的单个值。目标值导航标记为以下。

XDocument xdoc = XDocument.Load(responseStream);

string totalListings = xdoc.Element("findItemsAdvancedResponse").Element("paginationOutput").Element("totalEntries").Value;

我已经尝试过以上代码,但这不会起作用。它说 - '对象引用未设置为对象的实例。'

  

findItemsAdvancedResponse-> paginationOutput-> totalEntries-> “价值我   需要“

<?xml version='1.0' encoding='UTF-8'?>
<findItemsAdvancedResponse 
  xmlns="http://www.ebay.com/marketplace/search/v1/services">
  <ack>Success</ack>
  <version>1.13.0</version>
  <timestamp>2017-10-29T18:51:05.655Z</timestamp>
  <searchResult count="2">
    <item>
      <itemId>232328214987</itemId>
      <title>BRAND NEW Apple iPhone 6 Plus 5.5" Display 16GB GSM UNLOCKED Smartphone</title>
      <globalId>EBAY-US</globalId>
      <subtitle>BRAND NEW PHONE &amp; ACCESSORIES + RETAIL BOX</subtitle>
      <primaryCategory>
        <categoryId>9355</categoryId>
        <categoryName>Cell Phones &amp; Smartphones</categoryName>
      </primaryCategory>
      <galleryURL>http://thumbs4.ebaystatic.com/pict/232328214987404000000002_1.jpg</galleryURL>
      <viewItemURL>http://www.ebay.com/itm/BRAND-NEW-Apple-iPhone-6-Plus-5-5-Display-16GB-GSM-UNLOCKED-Smartphone-/232328214987?var=531582721516&amp;vti=</viewItemURL>
      <paymentMethod>PayPal</paymentMethod>
      <autoPay>true</autoPay>
      <postalCode>20879</postalCode>
      <location>Gaithersburg,MD,USA</location>
      <country>US</country>
      <sellerInfo>
        <sellerUserName>buyspry</sellerUserName>
        <feedbackScore>141448</feedbackScore>
        <positiveFeedbackPercent>98.5</positiveFeedbackPercent>
        <feedbackRatingStar>RedShooting</feedbackRatingStar>
        <topRatedSeller>true</topRatedSeller>
      </sellerInfo>
      <shippingInfo>
        <shippingServiceCost currencyId="USD">0.0</shippingServiceCost>
        <shippingType>Free</shippingType>
        <shipToLocations>Worldwide</shipToLocations>
        <expeditedShipping>true</expeditedShipping>
        <oneDayShippingAvailable>true</oneDayShippingAvailable>
        <handlingTime>1</handlingTime>
      </shippingInfo>
      <sellingStatus>
        <currentPrice currencyId="USD">329.99</currentPrice>
        <convertedCurrentPrice currencyId="USD">329.99</convertedCurrentPrice>
        <sellingState>Active</sellingState>
        <timeLeft>P6DT2H48M24S</timeLeft>
      </sellingStatus>
      <listingInfo>
        <bestOfferEnabled>false</bestOfferEnabled>
        <buyItNowAvailable>false</buyItNowAvailable>
        <startTime>2017-05-08T21:39:29.000Z</startTime>
        <endTime>2017-11-04T21:39:29.000Z</endTime>
        <listingType>FixedPrice</listingType>
        <gift>false</gift>
        <watchCount>2518</watchCount>
      </listingInfo>
      <returnsAccepted>true</returnsAccepted>
      <condition>
        <conditionId>1000</conditionId>
        <conditionDisplayName>New</conditionDisplayName>
      </condition>
      <isMultiVariationListing>true</isMultiVariationListing>
      <topRatedListing>true</topRatedListing>
    </item>
    <item>
      <itemId>332182393939</itemId>
      <title>Apple iPhone 6 (Factory Unlocked) AT&amp;T Verizon T-Mobile Gray Gold Silver $20 OFF</title>
      <globalId>EBAY-US</globalId>
      <subtitle>Top US Seller | $20 OFF INSTANTLY| Warranty | Case&amp;SP</subtitle>
      <primaryCategory>
        <categoryId>9355</categoryId>
        <categoryName>Cell Phones &amp; Smartphones</categoryName>
      </primaryCategory>
      <galleryURL>http://thumbs4.ebaystatic.com/pict/332182393939404000000003_3.jpg</galleryURL>
      <viewItemURL>http://www.ebay.com/itm/Apple-iPhone-6-Factory-Unlocked-AT-T-Verizon-T-Mobile-Gray-Gold-Silver-20-OFF-/332182393939?var=541215921735&amp;vti=</viewItemURL>
      <paymentMethod>PayPal</paymentMethod>
      <autoPay>true</autoPay>
      <location>USA</location>
      <country>US</country>
      <sellerInfo>
        <sellerUserName>cocosprinkles</sellerUserName>
        <feedbackScore>22252</feedbackScore>
        <positiveFeedbackPercent>99.6</positiveFeedbackPercent>
        <feedbackRatingStar>YellowShooting</feedbackRatingStar>
        <topRatedSeller>true</topRatedSeller>
      </sellerInfo>
      <shippingInfo>
        <shippingServiceCost currencyId="USD">0.0</shippingServiceCost>
        <shippingType>Free</shippingType>
        <shipToLocations>Worldwide</shipToLocations>
        <expeditedShipping>true</expeditedShipping>
        <oneDayShippingAvailable>false</oneDayShippingAvailable>
        <handlingTime>1</handlingTime>
      </shippingInfo>
      <sellingStatus>
        <currentPrice currencyId="USD">319.99</currentPrice>
        <convertedCurrentPrice currencyId="USD">319.99</convertedCurrentPrice>
        <sellingState>Active</sellingState>
        <timeLeft>P10DT21H5M41S</timeLeft>
      </sellingStatus>
      <listingInfo>
        <bestOfferEnabled>false</bestOfferEnabled>
        <buyItNowAvailable>false</buyItNowAvailable>
        <startTime>2017-04-13T15:56:46.000Z</startTime>
        <endTime>2017-11-09T15:56:46.000Z</endTime>
        <listingType>StoreInventory</listingType>
        <gift>false</gift>
        <watchCount>90</watchCount>
      </listingInfo>
      <returnsAccepted>true</returnsAccepted>
      <galleryPlusPictureURL>http://galleryplus.ebayimg.com/ws/web/332182393939_1_3_1_00000003.jpg</galleryPlusPictureURL>
      <condition>
        <conditionId>2000</conditionId>
        <conditionDisplayName>Manufacturer refurbished</conditionDisplayName>
      </condition>
      <isMultiVariationListing>true</isMultiVariationListing>
      <topRatedListing>true</topRatedListing>
    </item>
  </searchResult>
  <paginationOutput>
    <pageNumber>1</pageNumber>
    <entriesPerPage>2</entriesPerPage>
    <totalPages>47873</totalPages>
    <totalEntries>95746</totalEntries>
  </paginationOutput>
  <itemSearchURL>http://www.ebay.com/sch/9355/i.html?fsaspfilter=Brand%3DApple&amp;fscurrency=USD&amp;Brand%255Cu0007=Apple&amp;aspectrequest=1&amp;_ddo=1&amp;_ipg=2&amp;_mPrRngCbx=1&amp;_os=S%7CD&amp;_pgn=1&amp;_udhi=500&amp;_udlo=50</itemSearchURL>
</findItemsAdvancedResponse>

1 个答案:

答案 0 :(得分:1)

您获得异常的原因是,xdoc.Element("findItemsAdvancedResponse")正在返回NULL并且您正在尝试在NULL上调用另一个方法,因此获得典型的空引用异常, & #34;对象引用未设置为对象的实例 &#34;。

您获取null的原因是,您的XML具有命名空间,因此当您访问XML元素时,您应该使用命名空间以及您要查找的元素名称。

这应该有效。

var path = Server.MapPath("~/Content/YourXmlFile.xml");
var xdoc = XDocument.Load(path);

XNamespace ns = "http://www.ebay.com/marketplace/search/v1/services";

var totalEntries = xdoc?.Element(ns + "findItemsAdvancedResponse")
                  ?.Element(ns + "paginationOutput")?.Element(ns + "totalEntries")?.Value;

如果您使用XElement,则可以跳过外部xml元素(findItemsAdvancedResponse)并从下一级开始查看。

var path = Server.MapPath("~/Content/YourXmlFile.xml");
var xdoc = XElement.Load(path);

XNamespace ns = "http://www.ebay.com/marketplace/search/v1/services";

var totalEntries = xdoc?.Element(ns + "paginationOutput")?.
                                                   Element(ns + "totalEntries")?.Value;