如何使用linq获取指定用户名的密码值? 例如,如果Username等于AAAA,那么passsword就是ss。
<?xml version="1.0" encoding="utf-8"?>
<User>
<Username>AAAA</Username>
<Password>ss</Password>
</User>
<User>
<Username>CCC</Username>
<Password>zzz</Password>
</User>
答案 0 :(得分:1)
我首先要说你应该将你的xml结构改为:
<?xml version="1.0" encoding="utf-8"?>
<users>
<User>
<Username>AAAA</Username>
<Password>ss</Password>
</User>
<User>
<Username>CCC</Username>
<Password>zzz</Password>
</User>
</users>
然后你可以尝试:
var username = "AAAA";
var password = XElement.Parse(xml)
.Elements("User")
.Where(x=>(string)x.Element("Username") == username)
.Select(x=>(string)x.Element("Password"));
我倾向于使用XElement
,但有些人会说XDocument
更好:
var xdoc = XDocument.Parse(xml);
var username = "AAAA";
var password = xdoc.Root.Elements("User")
.Where(x=>(string)x.Element("Username") == username)
.Select(x=>(string)x.Element("Password"))
.FirstOrDefault();