curiousDev
curiousDev

Reputation: 437

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.

Upvotes: 0

Views: 913

Answers (5)

Shreya
Shreya

Reputation: 204

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

Upvotes: 0

It&#39;sNotALie.
It&#39;sNotALie.

Reputation: 22794

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

Upvotes: 0

Suraj Singh
Suraj Singh

Reputation: 4059

    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; 

Upvotes: 0

cuongle
cuongle

Reputation: 75306

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

Upvotes: 2

DGibbs
DGibbs

Reputation: 14618

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

Upvotes: -1

Related Questions