【问题标题】:XML Document to IEnumerable<XElement> and get valuesXML 文档到 IEnumerable<XElement> 并获取值
【发布时间】:2016-07-21 19:31:07
【问题描述】:

大家好,我正试图从我的 xdocument 中更深的容器中获取一些值,但我总是在 Nullreference 中运行。

这是我目前的代码:

                StreamReader xmlStream = new StreamReader(rsp.GetResponseStream());
            string XMLstr = xmlStream.ReadToEnd();
            XDocument xelement = XDocument.Parse(XMLstr);
            xmlStream.Close();


            IEnumerable<XElement> items = xelement.Elements();

            foreach (var item in items )
            {
                Console.WriteLine(item.Element("ItemID").Value.ToString());
            }

这是我要使用的 XML:

    <GetSellerListResponse xmlns="urn:ebay:apis:eBLBaseComponents">
  <Timestamp>2016-02-26T22:02:38.968Z</Timestamp>
  <Ack>Success</Ack>
  <Version>967</Version>
  <Build>967_CORE_BUNDLED_10708779_R1</Build>
  <PaginationResult>
    <TotalNumberOfPages>14</TotalNumberOfPages>
    <TotalNumberOfEntries>27</TotalNumberOfEntries>
  </PaginationResult>
  <HasMoreItems>true</HasMoreItems>
  <ItemArray>
    <Item>
      <AutoPay>false</AutoPay>
      <BuyerProtection>ItemIneligible</BuyerProtection>
      <Country>US</Country>
      <Currency>USD</Currency>
      <HitCounter>NoHitCounter</HitCounter>
      <ItemID>110043597553</ItemID>
      <ListingDetails>
        <StartTime>2016-02-12T23:35:27.000Z</StartTime>
        <EndTime>2016-02-19T23:35:27.000Z</EndTime>
        <ViewItemURL>http://cgi.sandbox.ebay.com/ws/eBayISAPI.dll?ViewItem&
           item=110043597553&category=41393</ViewItemURL>
        <HasUnansweredQuestions>false</HasUnansweredQuestions>
        <HasPublicMessages>false</HasPublicMessages>
        <BuyItNowAvailable>true</BuyItNowAvailable>
      </ListingDetails>
      <ListingDuration>Days_7</ListingDuration>
      <Location>Santa Cruz, California</Location>
      <PrimaryCategory>
        <CategoryID>41393</CategoryID>
        <CategoryName>Collectibles:Decorative Collectibles:Other</CategoryName>
      </PrimaryCategory>
      <Quantity>1</Quantity>
      <ReviseStatus>
        <ItemRevised>false</ItemRevised>
      </ReviseStatus>
      <SecondaryCategory>
        <CategoryID>95116</CategoryID>
        <CategoryName>Collectibles:Disneyana:Contemporary (1968-Now):Bobblehead Figures</CategoryName>
      </SecondaryCategory>
      <SellingStatus>
        <BidCount>0</BidCount>
        <BidIncrement currencyID="USD">0.5</BidIncrement>
        <ConvertedCurrentPrice currencyID="USD">11.49</ConvertedCurrentPrice>
        <CurrentPrice currencyID="USD">11.49</CurrentPrice>
        <MinimumToBid currencyID="USD">11.49</MinimumToBid>
        <QuantitySold>0</QuantitySold>
        <SecondChanceEligible>false</SecondChanceEligible>
        <ListingStatus>Completed</ListingStatus>
      </SellingStatus>
      <ShipToLocations>US</ShipToLocations>
      <Site>US</Site>
      <Storefront>
        <StoreCategoryID>1</StoreCategoryID>
        <StoreCategory2ID>0</StoreCategory2ID>
        <StoreURL>http://www.stores.sandbox.ebay.com/id=132854966</StoreURL>
      </Storefront>
      <SubTitle>Micky, with the ears!</SubTitle>
      <TimeLeft>PT0S</TimeLeft>
      <Title>Kelly's Kitsch</Title>
      <WatchCount>0</WatchCount>
      <PostalCode>95062</PostalCode>
      <PictureDetails>
        <GalleryURL>http://thumbs.ebaystatic.com/pict/41007087008080_0.jpg</GalleryURL>
        <PhotoDisplay>None</PhotoDisplay>
        <PictureURL>http://thumbs.ebaystatic.com/pict/41007087008080_0.jpg</PictureURL>
      </PictureDetails>
      <ProxyItem>false</ProxyItem>
      <ReturnPolicy>
        <RefundOption>MoneyBack</RefundOption>
        <Refund>Money Back</Refund>
        <ReturnsWithinOption>Days_30</ReturnsWithinOption>
        <ReturnsWithin>30 Days</ReturnsWithin>
        <ReturnsAcceptedOption>ReturnsAccepted</ReturnsAcceptedOption>
        <ReturnsAccepted>Returns Accepted</ReturnsAccepted>
        <Description>Returns accepted only if item is not as described.</Description>
        <ShippingCostPaidByOption>Buyer</ShippingCostPaidByOption>
        <ShippingCostPaidBy>Buyer</ShippingCostPaidBy>
      </ReturnPolicy>
      <PaymentAllowedSite>US</PaymentAllowedSite>
    </Item>
   </ItemArray>
  <ItemsPerPage>2</ItemsPerPage>
  <PageNumber>1</PageNumber>
  <ReturnedItemCountActual>2</ReturnedItemCountActual>
</GetSellerListResponse>

谁能解释一下我错过了什么?

谢谢

【问题讨论】:

    标签: xml linq xelement


    【解决方案1】:

    您在XDocument 上调用Elements(),所以这只是要返回根元素。

    然后您在该根元素上调用 Element("ItemID") - 请求一个不存在的元素。所以这将返回null,导致您的异常。此外,您忽略了所有元素都在命名空间中这一事实。

    看起来你可能真的想要 Item 元素,所以你可以使用:

    // Changed the variable name to match what it is...
    XDocument doc = XDocument.Parse(XMLstr);
    XNamespace ns = "urn:ebay:apis:eBLBaseComponents";
    Enumerable<XElement> items = doc.Descendants(ns + "Item");
    foreach (var item in items)
    {
        // XElement.Value is already a string; no need to call ToString on it
        Console.WriteLine(item.Element(ns + "ItemID").Value);
    }
    

    另一种方法是专门查找ItemArray 元素及其Item 子元素:

    XDocument doc = XDocument.Parse(XMLstr);
    XNamespace ns = "urn:ebay:apis:eBLBaseComponents";
    Enumerable<XElement> items = doc.Root
                                    .Element(ns + "ItemArray")
                                    .Elements(ns + "Item");
    // Code as before
    

    【讨论】:

    • 你是对的。我已经尝试了很多,我已经完全搞砸了代码。我已经尝试了第一个代码。但它只返回一个元素。如果有更多的“物品”容器怎么办?
    • @josef_skywalker:然后它会循环很多次。但是您提供的示例 XML 只有一个 Item 元素。
    【解决方案2】:

    致任何发现此内容的 VB 用户。首先要注意有一个命名空间,因此考虑到这一点的最简单方法之一是添加 Imports 语句。

    Imports <xmlns="urn:ebay:apis:eBLBaseComponents">
    

    接下来解析响应。

    Dim someXE As XElement = XElement.Parse(XMLstr)
    

    然后选择所有 ItemID,无论它们位于何处

    Dim itemID As IEnumerable(Of XElement) = someXE...<ItemID>
    

    最后再单独看看它们

    For Each id As XElement In itemID
        Debug.WriteLine(id.Value) 'from example above 110043597553
    Next
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-05
      • 1970-01-01
      相关资源
      最近更新 更多