问题描述
- asp.net 如何读取 这样的XML 取得它的loginname和realname
-
<cas:serviceResponse xmlns:cas='http://www.yale.edu/tp/cas'> <cas:authenticationSuccess> <cas:user>bb</cas:user> <cas:attributes nid='1'> <cas:id>2</cas:id> <cas:loginname>bb</cas:loginname> <cas:role>2</cas:role> <cas:realname>bbggg</cas:realname> </cas:attributes> </cas:authenticationSuccess> </cas:serviceResponse>
解决方案
```void Main()
{
string xml = @"
cas:userbb/cas:user
cas:id2/cas:id
cas:loginnamebb/cas:loginname
cas:role2/cas:role
cas:realnamebbggg/cas:realname
/cas:attributes
/cas:authenticationSuccess
/cas:serviceResponse";
XDocument xmlPage = XDocument.Parse(xml);
XNamespace ns = "http://www.xxx.edu/tp/cas";
var query = from x in xmlPage.Descendants(ns+"authenticationSuccess")
from y in x.Element(ns+"attributes").Elements()
select y;
foreach(XElement item in query)
Console.WriteLine("{0}:t {1}",item.Name.LocalName,item.Value);
/*
id: 2
loginname: bb
role: 2
realname: bbggg
*/
}
解决方案二:
void Main()
{
string xml = @" <cas:serviceResponse xmlns:cas='http://www.yale.edu/tp/cas'>
<cas:authenticationSuccess>
<cas:user>bb</cas:user>
<cas:attributes nid='1'>
<cas:id>2</cas:id>
<cas:loginname>bb</cas:loginname>
<cas:role>2</cas:role>
<cas:realname>bbggg</cas:realname>
</cas:attributes>
</cas:authenticationSuccess>
</cas:serviceResponse>";
XDocument xmlPage = XDocument.Parse(xml);
XNamespace ns = "http://www.yale.edu/tp/cas";
var query = from x in xmlPage.Descendants(ns+"authenticationSuccess")
select new
{
loginname = x.Element(ns+"attributes").Element(ns+"loginname").Value,
realname = x.Element(ns+"attributes").Element(ns+"realname").Value
};
}
解决方案三:
你的问题主要还是在 XNamespace
解决方案四:
如果attatributes下节目未知,直接这样:
var query = from x in xmlPage.Descendants(ns+"authenticationSuccess")
select x.Element(ns+"attributes");
解决方案五:
参考这个:
void Main()
{
string xml = @" <cas:serviceResponse xmlns:cas='http://www.xxx.edu/tp/cas'>
<cas:authenticationSuccess>
<cas:user>bb</cas:user>
<cas:attributes nid='1'>
<cas:id>2</cas:id>
<cas:loginname>bb</cas:loginname>
<cas:role>2</cas:role>
<cas:realname>bbggg</cas:realname>
</cas:attributes>
</cas:authenticationSuccess>
</cas:serviceResponse>";
XDocument xmlPage = XDocument.Parse(xml);
XNamespace ns = "http://www.xxx.edu/tp/cas";
var query = from x in xmlPage.Descendants(ns+"authenticationSuccess")
from y in x.Element(ns+"attributes").Elements()
select y;
foreach(XElement item in query)
Console.WriteLine("{0}:t {1}",item.Name.LocalName,item.Value);
/*
id: 2
loginname: bb
role: 2
realname: bbggg
*/
}
时间: 2024-09-11 20:28:50