/ / Durchsuchen Sie XML-Dokumente mit LINQ - c #, xml, linq

Durchsuchen Sie das XML-Dokument mit LINQ - c #, xml, linq

Ich habe ein ähnliches XML-Dokument:

<Root>

<MainItem ID="1">
<SubItem></SubItem>
<SubItem></SubItem>
<SubItem></SubItem>
</MainItem>
<MainItem ID="2">
<SubItem></SubItem>
<SubItem></SubItem>
<SubItem></SubItem>
</MainItem>

...
</Root>

Ich möchte das gesamte MainItem-Element basierend auf dem Wert der Attribut-ID zurückgeben. Wenn also die Attribut-ID gleich 2 ist, geben Sie mir dieses MainItem-Element zurück.

Ich kann nicht herausfinden, wie ich das mit LINQ mache. Es scheint eine Menge Informationen auf Google zu geben, aber ich kann einfach nicht das finden, wonach ich suche.

Kleine Hilfe ?

TIA

:-)

Antworten:

2 für die Antwort № 1

Es könnte so etwas sein:

        XDocument doc = XDocument.Load("myxmlfile.xml");
XElement mainElement = doc.Element("Root")
.Elements("MainItem")
.First(e => (int)e.Attribute("ID") == 2);
// additional work

2 für die Antwort № 2

Wie wäre es damit:

// 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 für die Antwort № 3

Ich habe Ihr XML leicht geändert, um Werte zu erhalten:

<?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>

Und mit dieser 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 für die Antwort № 4

Von hier: Gewusst wie: Filtern nach einem Attribut (XPath-LINQ in 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"]");