简体   繁体   English

我如何使用linq查找XElement

[英]How can i find XElement using linq

I m working with c#. 我正在使用C#。

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

this is my xml. 这是我的xml。 And i wanna take Tifo. 我想要蒂芙。 I must use "Kod" nodes. 我必须使用“ Kod”节点。 eg XpathSelectelement("Kod").value = 1001 例如XpathSelectelement(“ Kod”)。value = 1001

Assuming every element has a <Kod> element, and they all contain valid integers, you could use: 假设每个元素都有一个<Kod>元素,并且它们都包含有效的整数,则可以使用:

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... 这将为您提供具有与Kod元素匹配值的XElement集合。

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). 您可以只在XPath语句中使用值,在这种情况下为1001。dahlbyk的答案和Thorarin的答案都应同样起作用(除非您已经拥有不需要作为类型变量的int的值,所以我将对其进行比较) 。

I just thought that I would post a simple one line solution to offer options. 我只是以为我会发布一种简单的单行解决方案来提供选项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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