get xelement attribute value
70,638
Solution 1
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"
Solution 2
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.
Solution 3
from the docs for XAttribute.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
orNullable<T>
ofInt32
. If the attribute does not exist, then the nullable type is set to null.
Comments
-
LFurness over 3 years
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); }