Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get xelement attribute value

I have an XElement that looks like this:

<User ID="11" Name="Juan Diaz" LoginName="DN1\jdiaz" xmlns="http://schemas.microsoft.com/sharepoint/soap/directory/" /> 

How can I use XML to extract the value of the LoginName attribute? I tried the following, but the q2 "Enumeration yielded no results".

var q2 = from node in el.Descendants("User")     let loginName = node.Attribute(ns + "LoginName")     select new { LoginName = (loginName != null) }; foreach (var node in q2) {     Console.WriteLine("LoginName={0}", node.LoginName); } 
like image 260
LFurness Avatar asked Jul 22 '13 13:07

LFurness


People also ask

How do I get XElement attribute value?

Value: If you are getting the value and the attribute might not exist, it is more convenient to use the explicit conversion operators, and assign the attribute to a nullable type such as string or Nullable<T> of Int32 . If the attribute does not exist, then the nullable type is set to null.

What is XElement C#?

The XElement class is one of the fundamental classes in LINQ to XML. It represents an XML element. The following list shows what you can use this class for: Create elements. Change the content of the element.


2 Answers

var xml = @"<User ID=""11""                    Name=""Juan Diaz""                    LoginName=""DN1\jdiaz""                    xmlns=""http://schemas.microsoft.com/sharepoint/soap/directory/"" />";  var user = XElement.Parse(xml); var login = user.Attribute("LoginName").Value; // "DN1\jdiaz" 
like image 107
Sergey Berezovskiy Avatar answered Oct 07 '22 03:10

Sergey Berezovskiy


XmlDocument doc = new XmlDocument(); doc.Load("myFile.xml"); //load your xml file XmlNode user = doc.getElementByTagName("User"); //find node by tag name   string login = user.Attributes["LoginName"] != null ? user.Attributes["LoginName"].Value : "unknown login"; 

The last line of code, where it's setting the string login, the format looks like this...

var variable = condition ? A : B; 

It's basically saying that if condition is true, variable equals A, otherwise variable equals B.

like image 31
sora0419 Avatar answered Oct 07 '22 03:10

sora0419