Bul*_*nes 3 .net c# linq linq-to-xml
素不相识的!
我有一些看起来像这样的XML:
<Root>
<SectionA>
<Item id="111">
<Options>
<Option val="a" cat="zzz">
<Package value="apple" />
<Feature value="avacado" />
</Option>
<Option val="b" cat="yyy">
<Package value="banana" />
<Feature value="blueberry" />
</Option>
</Options>
</Item>
<Item id="222">
<Options>
<Option val="c" cat="xxx">
<Package value="carrot" />
<Feature value="cucumber" />
</Option>
<Option val="d" cat="www">
<Package value="dairy" />
<Feature value="durom" />
</Option>
</Options>
</Item>
</SectionA>
<SectionB>
.
.
.
</SectionB>
</Root>
Run Code Online (Sandbox Code Playgroud)
我想根据ITEM的ID属性为"111"得到PACKAGE和FEATURE值,OPTION的VAL属性为"a".
我不知道从哪里开始.我可以使用where选择ITEM节点,但我不确定如何将它与OPTION节点上的where子句相结合.有任何想法吗?
这适合我.
var doc = XDocument.Parse(s);
var items = from item in doc.Descendants("Item")
where item.Attribute("id").Value == "111"
from option in item.Descendants("Option")
where option.Attribute("val").Value == "a"
let package = option.Element("Package").Attribute("value")
let feature = option.Element("Feature").Attribute("value")
select new { Package = package.Value, Feature = feature.Value };
items.First().Feature; // = "avacado"
items.First().Package; // = "apple"
Run Code Online (Sandbox Code Playgroud)
let如果需要,可以省略这些部分,它们只是为了使匿名类型更薄.
var items = from item in doc.Descendants("Item")
where item.Attribute("id").Value == "111"
from option in item.Descendants("Option")
where option.Attribute("val").Value == "a"
select new
{
Package = option.Element("Package").Attribute("value").Value,
Feature = option.Element("Feature").Attribute("value").Value
};
Run Code Online (Sandbox Code Playgroud)
实际上,我有点像第二个.
而非查询Linq风格.
var items = doc.Descendants("Item")
.Where(item => item.Attribute("id").Value == "111")
.SelectMany(item => item.Descendants("Option"))
.Where(option => option.Attribute("val").Value == "a")
.Select(option => new
{
Package = option.Element("Package").Attribute("value").Value,
Feature = option.Element("Feature").Attribute("value").Value
});
Run Code Online (Sandbox Code Playgroud)