Mam dokument xml podobny do tego:
<Root>
<MainItem ID="1">
<SubItem></SubItem>
<SubItem></SubItem>
<SubItem></SubItem>
</MainItem>
<MainItem ID="2">
<SubItem></SubItem>
<SubItem></SubItem>
<SubItem></SubItem>
</MainItem>
...
</Root>
Chcę zwrócić cały element MainItem na podstawie wartości identyfikatora atrybutu. Tak skutecznie, jeśli identyfikator atrybutu jest równy 2, a następnie daj mi ten element MainItem z powrotem.
Nie mogę się dowiedzieć, jak to zrobić z LINQ. Wygląda na to, że w Google jest mnóstwo informacji, ale po prostu nie mogę znaleźć tego, czego szukam.
Drobna pomoc ?
TIA
:-)
Odpowiedzi:
2 dla odpowiedzi № 1Może to być coś takiego:
XDocument doc = XDocument.Load("myxmlfile.xml");
XElement mainElement = doc.Element("Root")
.Elements("MainItem")
.First(e => (int)e.Attribute("ID") == 2);
// additional work
2 dla odpowiedzi nr 2
Co powiesz na to:
// load your XML
XDocument doc = XDocument.Load(@"D:linq.xml");
// find element which has a ID=2 value
XElement mainItem = doc.Descendants("MainItem")
.Where(mi => mi.Attribute("ID").Value == "2")
.FirstOrDefault();
if(mainItem != null)
{
// do whatever you need to do
}
Marc
2 dla odpowiedzi nr 3
Zmieniłem trochę twój XML, by mieć wartości:
<?xml version="1.0"?>
<Root>
<MainItem ID="1">
<SubItem>value 1</SubItem>
<SubItem>val 2</SubItem>
<SubItem></SubItem>
</MainItem>
<MainItem ID="2">
<SubItem></SubItem>
<SubItem></SubItem>
<SubItem></SubItem>
</MainItem>
</Root>
I tym LINQ:
XDocument xmlDoc = XDocument.Load(@"C:test.xml");
var result = from mainitem in xmlDoc.Descendants("MainItem")
where mainitem.Attribute("ID").Value == "1"
select mainitem;
foreach (var subitem in result.First().Descendants())
{
Console.WriteLine(subitem.Value);
}
Console.Read();
0 dla odpowiedzi nr 4
Stąd: Jak: Filtruj atrybut (XPath-LINQ do XML)
// LINQ to XML query
IEnumerable<XElement> list1 =
from el in items.Descendants("MainItem")
where (string)el.Attribute("ID") == "2"
select el;
// XPath expression
IEnumerable<XElement> list2 = items.XPathSelectElements(".//MainItem[@ID="2"]");