tags:

views:

134

answers:

5

I have some xml like this:

<Action id="SignIn" description="nothing to say here" title=hello" />

Using LINQ to XML, how can I get the inner value of id? I am not on my dev machine (anothe machine with no dev stuff but so credentials) but I haven't tried:

 var x = from a in xe.Elements("Action")
     select a.Attribute("id").Value

Could I do something along those lines? I don't want a bool condition. Also, how would this be done using traditional XML methods before LINQ was introduced (I am on .NET 3.5 though).

Thanks

+2  A: 

Here is a small example that shows how to do it:

using System;
using System.Xml.Linq;

class Program
{
    static void Main()
    {
     String xml = @"<Action 
       id=""SignIn"" 
       description=""nothing to say here"" 
       title=""hello""/>";

     String id = XElement.Parse(xml)
      .Attribute("id").Value;
    }
}
Andrew Hare
+1  A: 

Using "traditional" XML methods you would do something this:

XmlDocument doc = new XmlDocument();
doc.Load("XML string here");

XmlNode node = doc.SelectSingleNode("Action");
string id = node.Attributes["id"].Value

Andrew has the right way to do this using Linq.

Scott Dorman
A: 

Using a traditional XML Document, assuming you already had the action node you wanted, by using SelectSingleNode, or by traversing the document, you could get the value of the id attribute with.

ActionNode.Attributes("id").Value
Kibbee
+3  A: 

You could do something like

XDocument doc = XDocument.Parse("<Action id=\"SignIn\" description=\"nothing to say here\" title=\"hello\" />");
var x = from a in doc.Elements("Action")
        select a.Attribute("id").Value;

string idValue = x.Single(); //Single() is called for this particular input assuming you IEnumerable has just one entry

With XmlDocument you could do

XmlDocument doc = new XmlDocument();
doc.LoadXml("<Action id=\"SignIn\" description=\"nothing to say here\" title=\"hello\" />");
var x = doc.SelectSingleNode("Action/@id");
string idValue = x.Value;

HTH

Fabrizio C.
Although I marked this as the answer, it doesn't work. My xml line is this: <?xml version="1.0" encoding="utf-8"?><opml version="1.0"> <head> <title>Feed Subscriptions</title> </head> <outline title="Omea News" text="Omea News" description="Latest news about JetBrains Omea product family" xmlUrl="http://jetbrains.com/omearss.xml" htmlUrl="http://www.jetbrains.com/omea" type="rss" />Perhaps I should use xpath?
dotnetdev
The argument of SelectSingleNode _is_ an XPath query.Can you explain more "it doesn't work"? What's the problem?The xml fragment you copy is not valid: it is not properly closed and there are semicolons between attributes.What do you want to extract from it?
Fabrizio C.
A: 

You pretty much have it, as long as 'xe' is the XElement that contains the one you are looking for and the "Action" element is the first/only "Action" element in the XElement:

string x = xe.Element("Action").Attribute("id").Value;

naspinski