简体   繁体   中英

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. eg XpathSelectelement("Kod").value = 1001

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;

Would this work?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM