简体   繁体   中英

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?

  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:

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

Gives: 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

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();

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