Выбор определенных значений из XML-документа в зависимости от других значений - PullRequest
0 голосов
/ 11 июля 2011

У меня есть следующий XML

<OrderReport>
  <Item>
    <Promotion>      
      <Component>
        <Type>Principal</Type>
        <Amount currency="USD">-0.25</Amount>
      </Component>
      <Component>
        <Type>Shipping</Type>
        <Amount currency="USD">0.00</Amount>
      </Component>
    </Promotion>
  </Item>
</OrderReport>

Мне нужно получить суммы для каждого типа. Вот то, что я пытаюсь

var q = from orders in xDoc.Descendants("OrderReport")    
        select new 
        {
            //This should return me the Principal Amount
            ItemDiscountAmount = orders.Element("Item")
                                       .Element("Promotion")
                                       .Element("Component")
                                       .Element("Amount")
                                       .Value,
            //This should return me the Principal Currency
            ItemDiscountCurrency = orders.Element("Item")
                                         .Element("Promotion")
                                         .Element("Component")
                                         .Element("Amount")
                                         .Attribute("currency")
                                         .Value,

            //This should return me the Shipping Amount
            ShipDiscountAmount = orders.Element("Item")
                                       .Element("Promotion")
                                       .Element("Component")
                                       .Element("Amount")
                                       .Value,
            //This should return me the Shipping Currency                        
            ShipDiscountCurrency = orders.Element("Item")
                                         .Element("Promotion")
                                         .Element("Component")
                                         .Element("Amount")
                                         .Attribute("currency")
                                         .Value,
        };

Код, который я написал, неверен. Он возвращает мне основную сумму и валюту для всех свойств прямо сейчас. Комментарии описывают то, что должно быть возвращено в нем для понимания цели. Запрос должен в основном возвращать мне цены и валюту в зависимости от узла <Type> в узле <Component>. Не уверен, как поставить условие в этом случае.

Ответы [ 2 ]

0 голосов
/ 12 июля 2011

Будет полезно, если вы сначала найдете элементы, которые содержат тип Principal или Shipping, а затем получите нужные значения. Я считаю, что это то, что вы после.

// using an XPATH will make this nicer to express
var query = from report in xDoc.Descendants("OrderReport")
            let principalAmount = report.XPathSelectElement("./*/*/Component[Type='Principal']/Amount")
            let shippingAmount = report.XPathSelectElement("./*/*/Component[Type='Shipping']/Amount")
            select new
            {
                ItemDiscountAmount = (decimal)principalAmount,
                ItemDiscountCurrency = (string)principalAmount.Attribute("currency"),
                ShipDiscountAmount = (decimal)shippingAmount,
                ShipDiscountCurrency = (string)shippingAmount.Attribute("currency"),
            };

Просто не забудьте включить пространство имен System.Xml.XPath, чтобы это работало.

0 голосов
/ 11 июля 2011

Вы просто должны добавить предложение Where,

var q = from orders in xdoc1.Descendants("OrderReport")
        join ItemPrices in xdoc1.Descendants 
        where orders.Component.Type == "Principal"
        select new 
        {
            OrderId = orders.Element("OrderID"),
            City = orders.Element("City"),
            CountryRegion = orders.Element("CountryCode"),
            State = orders.Element("StateOrRegion"),
            Street1 = orders.Element("AddressFieldOne"),
            Telephone = orders.Element("PhoneNumber"),
            ZipCode = orders.Element("PostalCode"),
            Name = orders.Element("Name"),
            OrderDate = orders.Element("OrderDate"),
            ShipMethod = orders.Element("FulfillmentMethod"),
            ItemCode = orders.Element("AmazonOrderItemCode"),
            SKU = orders.Element("SKU"),
            QtyOrdered = orders.Element(""),
            ItemTaxAmount = orders.Element(""),
            ItemTaxCurrency = orders.Element(""),
            ItemShipTaxAmount = orders.Element(""),
            ItemShipTaxCurrency = orders.Element(""),
            ItemTotalAmount = orders.Element(""),
            ItemTotalCurrency = orders.Element(""),
            ItemUnitPrice = orders.Element(""),
            ItemCommissionAmount = orders.Element(""),
            ItemCommissionCurrency = orders.Element("")
         };
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...