Linq-to-xml获取子节点

时间:2015-09-17 10:55:59

标签: c# xml linq linq-to-xml

我无法确定如何使用linq-to-xml从下面的xml中提取总价和个别价格(例如,我想得到票价以及所有价格的总和)。任何帮助都会非常受欢迎,特别是使用linq-to-xml的方法语法

我使用以下代码将数据加载到xDocument中,并使用xmlResponse对象来解析响应。

var xmlResponse = from element in xdoc.Descendants()
                              select element;

获取类似

的数据
xmlResponse.SingleOrDefault(x => x.Name.LocalName == "Registration")

以下是xwe响应的一个子集: -

<StateList>
    <State>
      <SourceJobID>J999999999999</SourceJobID>
      <TargetJobState>Complete</TargetJobState>
      <TargetJobID>11111111</TargetJobID>
      <TargetSystem>TESTSYSTEM</TargetSystem>
      <VehicleDetails>
        <Registration>TESTREGISRATION</Registration>
        <Plate>11111111111</Plate>
        <CO2Rating>160</CO2Rating>
        <Badge>1111111</Badge>
        <Description>TEST DESCRIPTION</Description>
      </VehicleDetails>
      <CompleteDetails>
        <CompletedOn>2015-09-15T13:39:11+01:00</CompletedOn>
        <JobDistance>0</JobDistance>
        <WaitingTime />
        <CO2Usage>0</CO2Usage>
        <ChargeList>
          <Charge>
            <Name>Airport Pickup</Name>
            <Currency>GBP</Currency>
            <Price>0.00</Price>
          </Charge>
          <Charge>
            <Name>Fare</Name>
            <Currency>GBP</Currency>
            <Price>0.00</Price>
          </Charge>
          <Charge>
            <Name>Extra Stops</Name>
            <Currency>GBP</Currency>
            <Price>0.00</Price>
          </Charge>
        </ChargeList>
      </CompleteDetails>
    </State>

2 个答案:

答案 0 :(得分:1)

假设您的示例中只有一个状态,您可以执行以下操作:

        decimal fare = decimal.Parse(xml.Descendants("Charge").Single(x => x.Element("Name").Value == "Fare").Element("Price").Value);
        decimal total = xml.Descendants("Charge").Sum(x => decimal.Parse(x.Element("Price").Value));

虽然如果列表中有一系列元素,则必须对其进行修改。

编辑:如果您在评论中说,您只想收取某些费用:

        // Valid names of charges to sum.
        string[] names = { "Airport Pickup", "Fare" };
        // Iterate over every state.
        foreach (var state in xml.Descendants("State")) 
        {
            // Get all charge elements in the current state whose names are contained in 'names' - then convert their 'Price' element to decimal and sum them.
            decimal stateTotal = state.Descendants("Charge").Where(x => names.Contains(x.Element("Name").Value)).Sum(x => decimal.Parse(x.Element("Price").Value)); 
        }

答案 1 :(得分:0)

if(doc.Descendants("Charge").Any())
{
    var FarePrice = doc.Descendants("Charge")
                .Where(x => x.Descendants("Name").First().Value.Equals("Fare")).First().Element("Price").Value;

    var Sum = doc.Descendants("Charge")
                .Select(x => Convert.ToDouble(x.Descendants("Price").First().Value))
                .Sum();     
    Console.WriteLine("Fare price:{0} Sum:{1}",FarePrice,Sum);
} 

它返回35作为10和25输入的总和。

在这里小提琴:https://dotnetfiddle.net/cuHXBn