[英]get xelement attribute value
I have an XElement that looks like this: 我有一个看起来像这样的XElement:
<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? 如何使用XML提取LoginName属性的值? I tried the following, but the q2 "Enumeration yielded no results". 我尝试了以下,但q2“枚举没有产生任何结果”。
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);
}
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"
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... 最后一行代码,它设置string login
,格式如下所示......
var variable = condition ? A : B;
It's basically saying that if condition is true
, variable equals A, otherwise variable equals B. 它基本上是说如果条件为true
,则变量等于A,否则变量等于B.
from the docs for XAttribute.Value: 来自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
. 如果获取值并且属性可能不存在,则使用显式转换运算符更方便,并将该属性分配给可空类型,例如Int32
string
或Nullable<T>
。 If the attribute does not exist, then the nullable type is set to null. 如果该属性不存在,则可空类型设置为null。
I ended up using string manipulation to get the value, so I'll post that code, but I would still like to see an XML approach if there is one. 我最终使用字符串操作来获取值,所以我将发布该代码,但如果有的话,我仍然希望看到XML方法。
string strEl = el.ToString();
string[] words = strEl.Split(' ');
foreach (string word in words)
{
if (word.StartsWith("LoginName"))
{
strEl = word;
int first = strEl.IndexOf("\"");
int last = strEl.LastIndexOf("\"");
string str2 = strEl.Substring(first + 1, last - first - 1);
//str2 = "dn1\jdiaz"
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.