I am trying to get a LINQ query to work by finding the Login information from an XML file where the parent has an attribute of type and I want the values of the elements underneath them. So without the XML tags what I have is:
Users
Username type=Test
Login testuser1
Password password
Username type=Test2
Login testuser2
Password password
Since I will need to pull many of these values out I'd like a func开发者_运维知识库tion where I can give it a type tag and have the correct value of the Login name returned, I've tried this a couple of different ways and haven't gotten LINQ to do what I want. I'm probably missing something but I am trying to go by the Microsoft examples, and some others but I haven't found anything quite like what I am trying to do to go by. I learn best by example and testing and so far I haven't gotten anything to work right.
I have tried two different versions of this:
public string getTestUserInfo(string type)
{
Assert.IsNotNullOrEmpty(type);
XElement root = XElement.Load("TestInformation.xml");
IEnumerable<XElement> myusername =
from el in root.Elements("Username")
where (string)el.Attribute("Type") == type
select el.Element("Login");
string username = myusername.ToString();
return username;
}
Which I was hoping would return the Username of type Test or Test2 depending on what I sent, then return me the el.Value of Login. I can't seem to get the syntax right to get the value. I also tried:
Assert.IsNotNullOrEmpty(type);
XElement root = XElement.Load("TestInformation.xml");
string username = (string)
(from el in root.Elements("Username")
where (string)el.Attribute("Type") == type
select el.Element("Login"));
return username;
But the string username = (string) line gives me errors about Can't convert XElement to string. If just want to get the first Login I can do it using root.Descendents, but I'd like to be able to call out any Login name I want just by type.
Is this doable?
In both cases, you are trying to cast an IEnumerable to a string. Try using .First to get the first Login element instead:
string username = root.Elements("Username")
.First(el => (string)el.Attribute("type") == type)
.Element("Login")
.Value;
One other thing to watch for. In your examples, you use the uppercase T on Attribute("Type"), but it is lower cased in the XML. XML like C# is case sensitive.
精彩评论