简体   繁体   English

如何使用LINQ获取xml中元素/元素下的属性值

[英]How to fetch attribute value under elements/elements in xml using LINQ

<test-case name="SuccessfulOneTimePayment" executed="True" result="Success" success="True" time="211.262" asserts="9">
  <categories>
    <category name="Regression" />
  </categories>
  <properties>
    <property name="TestcaseId" value="70592" />
  </properties>
</test-case>

Can anyone help me to fetch TestcaseId value=70592 from this xml? 任何人都可以帮我从这个xml中获取TestcaseId值= 70592吗?

  var testcaseid = xml.Root.Descendants("test-case").Elements("categories").Elements("properties")

 .Where(s => s.Attribute("name") != null)
 .ToList();

I tried the above code which is not helping me. 我尝试了上面没有帮助我的代码。

XDocument.Load(xml)
     .Descendants("property")
     .Where(e => (string)e.Attribute("name") == "TestcaseId")
     .Select(e => (string)e.Attribute("value"))
     .FirstOrDefault();

To get the value attribute you can use the following: 要获取value属性,您可以使用以下内容:

var foo = (from n in xml.Descendants("property")
           where n.Attribute("name").Value == "TestcaseId"
           select n.Attribute("value").Value).FirstOrDefault();

Gives: 70592 给: 70592

    XDocument newTrial = XDocument.Load(@"xxxxxxxxxxx\trial.xml");

     var value = from name in newTrial.Descendants("properties")
                    where name.Element("property").Attribute("name").Value != null && name.Element("property").Attribute("name").Value == "TestcaseId"  
                    select  name.Element("property").Attribute("value").Value; 
yourXDocument
    .Root
    .Element("properties")
    .SelectMany(x => x.Elements("property"))
    .Where(e => (string)e.Attribute("name") == "TestcaseId")
    .Select(e => (string)e.Attribute("value"))
    .FirstOrDefault(s => !string.IsNullOrEmpty(s));

I think you need to get list of the attribute "value" with in the element "property" whose other attribute "name" should note be null 我认为您需要在元素“property”中获取属性“value”的列表,其中“name”的其他属性应注意为null

You can try below code: 你可以尝试下面的代码:

var testcaseid1 = xdoc.Root.Descendants("property").Where(s => s.Attribute("name") != null).Select(s => s.Attribute("value").Value).ToList();

Or you can select the value of first occurrence using below code: 或者您可以使用以下代码选择第一次出现的值:

string testcaseid = xdoc.Root.Descendants("property").Where(s => s.Attribute("name") != null).Select(s => s.Attribute("value").Value).First();

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

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