给定以下xml:
<Location>
<LocationAttribute>
<OptionType>
<Code>02</Code>
<Description>RetailLocation</Description>
</OptionType>
<OptionCode>
<Code>03</Code>
<Description>Drop Box</Description>
</OptionCode>
</LocationAttribute>
<LocationAttribute>
<OptionType>
<Code>03</Code>
<Description>AdditionalServices</Description>
</OptionType>
<OptionCode>
<Category>06</Category>
<Code>031</Code>
<Name>**Find a drop off location**</Name>
</OptionCode>
<OptionCode>
<Category>07</Category>
<Code>001</Code>
<Name>**Ground**</Name>
</OptionCode>
<OptionCode>
<Category>07</Category>
<Code>002</Code>
<Name>**Air**</Name>
</OptionCode>
</LocationAttribute>
</Location>
当OptionType的代码为3时,我如何解析出每个选项代码的Name属性的值?我一直在尝试:
List<string> services = item.Descendants("LocationAttribute")
.Where(service => service.Element("OptionType").Value == "3")
.Select(service => service.Element("OptionCode").Element("Description").Value).ToList()
你需要做一个SelectMany
。在Select
中,每个OptionCode Elements
的名称Element
的Value
。此外,您还必须检查OptionType Element
的代码Element
的Value
,并且由于它是string
比较,您必须包括前导"0"。
var services = item.Descendants("LocationAttribute")
.Where(loc => loc.Element("OptionType").Element("Code").Value == "03")
.SelectMany(loc => loc.Elements("OptionCode")
.Select(code => code.Element("Name").Value));