tags:

views:

333

answers:

3

Hi there. 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

A: 

Would this work?

XElement root = XElement.Parse("...");
var tifo = (
    from kod in root.Descendants("Kod")
    where kod.Value == "1001"
    select kod.Parent
    ).First();
dahlbyk
it returns null..
cagin
Try select kod instead of kod.Parent - still null? First() should throw an exception if the query didn't match anything, so I would be really surprised to see a null value returned...
dahlbyk
+1  A: 

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;
Thorarin
A: 

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.

Brian ONeil