cagin
cagin

Reputation: 5920

How can i find XElement using linq

I m working with c#.

<Tüberkiloz>
    <Kod>
      1000
    </Kod>
  </Tüberkiloz>
  <Tifo>
    <Kod>
      1001
    </Kod>
  </Tifo>
  <Bakteriyel_Endokardit>
    <Kod>
      1002
    </Kod>
  </Bakteriyel_Endokardit>

this is my xml. And i wanna take Tifo. I must use "Kod" nodes. e.g XpathSelectelement("Kod").value = 1001

Upvotes: 1

Views: 3558

Answers (3)

Brian ONeil
Brian ONeil

Reputation: 4339

This will get you a collection of XElements that have matching values for the Kod element...

var doc = XDocument.Parse(@"
                <root>
                <Tüberkiloz>
                    <Kod>1000</Kod>
                </Tüberkiloz>
                <Tifo>
                  <Kod>1001</Kod>
                </Tifo>
                <Bakteriyel_Endokardit>
                  <Kod>1002</Kod>
                </Bakteriyel_Endokardit>
                </root>");

var matchingElements = doc.XPathSelectElements("root/*[./Kod/text() = '1001']");  

you can just use the value in the XPath statement, in this case 1001. dahlbyk's answer and Thorarin's answer should both work as well (unless you have your value as an int already you don't need to cast, I would just compare it).

I just thought that I would post a simple one line solution to offer options.

Upvotes: 0

Thorarin
Thorarin

Reputation: 48476

Assuming every element has a <Kod> element, and they all contain valid integers, you could use:

var doc = XDocument.Parse(@"
    <root>
    <Tüberkiloz>
        <Kod>1000</Kod>
    </Tüberkiloz>
    <Tifo>
      <Kod>1001</Kod>
    </Tifo>
    <Bakteriyel_Endokardit>
      <Kod>1002</Kod>
    </Bakteriyel_Endokardit>
    </root>");

var matches = from el in doc.Root.Elements()
              where (int)(el.Element("Kod")) == 1001
              select el;

Upvotes: 1

dahlbyk
dahlbyk

Reputation: 77530

Would this work?

XElement root = XElement.Parse("...");
var tifo = (
    from kod in root.Descendants("Kod")
    where kod.Value == "1001"
    select kod.Parent
    ).First();

Upvotes: 0

Related Questions