2013-07-22 69 views
21

我有一个看起来像这样的的XElement:得到的XElement属性值

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

如何使用XML来提取的LoginName属性的值?我尝试了以下,但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); 
} 

回答

26
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" 
+0

请注意,XAttribute可以为null(这里不是),所以可能希望在获取值之前进行空检查。 – user420667

0

我结束了使用字符串操作来获取值,所以我会张贴代码,但我仍然希望看到一种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" 
    } 
} 
+4

不要对XML进行字符串操作。 XML通常看起来很简单,但事实并非如此。因此,请使用Microsoft提供的工具来解析它。 –

4
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"; 

的最后一行代码,它的设置的string login,格式看起来像这样...

var variable = condition ? A : B; 

它基本上是说,如果条件是true,变等于A,否则变量等于B.

+0

最后一个字符串应该是: 'string login = user.Attributes?[“LoginName”] ?? “未知登录名”;' –

2

from the docs for XAttribute.Value:

如果你所得到的值和属性可能不存在,更方便使用显式转换操作符,属性分配给可空类型,如stringInt32Nullable<T>。如果该属性不存在,则可空类型设置为null。

+0

以及引用文档[link]中的第二个示例(https://msdn.microsoft.com/en-us/library/system.xml.linq.xattribute.value(v = vs.110 ).aspx)演示了转换运算符的用法。 –