LINQ ~ XML 초보자 질문 : 둘 이상의 결과를 반환
-
02-07-2019 - |
문제
인사말!
나는 Linq 주위에 머리를 감싸기 위해 노력하고 있습니다. 이와 같은 XML이 XDocument 객체에로드 된 경우 :
<Root>
<GroupA>
<Item attrib1="aaa" attrib2="000" attrib3="true" />
</GroupA>
<GroupB>
<Item attrib1="bbb" attrib2="111" attrib3="true" />
<Item attrib1="ccc" attrib2="222" attrib3="false" />
<Item attrib1="ddd" attrib2="333" attrib3="true" />
</GroupB>
<GroupC>
<Item attrib1="eee" attrib2="444" attrib3="true" />
<Item attrib1="fff" attrib2="555" attrib3="true" />
</GroupC>
</Root>
그룹 요소의 모든 항목 자식 요소의 속성 값을 얻고 싶습니다. 내 쿼리의 모습은 다음과 같습니다.
var results = from thegroup in l_theDoc.Elements("Root").Elements(groupName)
select new
{
attrib1_val = thegroup.Element("Item").Attribute("attrib1").Value,
attrib2_val = thegroup.Element("Item").Attribute("attrib2").Value,
};
쿼리는 작동하지만 예를 들어 GroupName 변수에는 "GroupB"가 포함 된 경우 하나의 결과 (첫 번째 항목 요소) 만 3 대신 반환됩니다. 내가 뭔가를 놓치고 있습니까?
해결책
XElement e = XElement.Parse(testStr);
string groupName = "GroupB";
var items = from g in e.Elements(groupName)
from i in g.Elements("Item")
select new {
attr1 = (string)i.Attribute("attrib1"),
attr2 = (string)i.Attribute("attrib2")
};
foreach (var item in items)
{
Console.WriteLine(item.attr1 + ":" + item.attr2);
}
다른 팁
예, .element ()는 첫 번째 일치 요소 만 반환합니다. .elements ()를 원하고 쿼리를 약간 다시 작성해야합니다.
var results = from group in l_theDoc.Root.Elements(groupName)
select new
{
items = from i in group.Elements("Item")
select new
{
attrib1_val = i.Attribute("attrib1").Value,
attrib2_val = i.Attribute("attrib2").Value
}
};
다음은 답의 쿼리 방법 형식입니다.
var items =
e.Elements("GroupB")
.SelectMany(g => g.Elements("Item"))
.Select(i => new {
attr1 = i.Attribute("attrib1").Value,
attr2 = i.Attribute("attrib2").Value,
attr3 = i.Attribute("attrib3").Value
} )
.ToList()
또 다른 가능성은 WHERE 절을 사용하는 것입니다.
var groupName = "GroupB";
var results = from theitem in doc.Descendants("Item")
where theitem.Parent.Name == groupName
select new
{
attrib1_val = theitem.Attribute("attrib1").Value,
attrib2_val = theitem.Attribute("attrib2").Value,
};
제휴하지 않습니다 StackOverflow