我有一个字符串变量(getUserRoles
),其中包含以下内容:
<role name="olvers" guid="ee81e26aeb7cd" description="Used at"
isdynamic="false">
<extradata>
</extradata>
<include>
<users>
<user name="Q:www\sitename1" />
<user name="Q:www\sitename2" />
<user name="Q:"Q:www\sitename3" />
</users>
<groups />
<smartobjects />
</include>
<exclude>
<users />
<groups />
<smartobjects />
</exclude>
</role>
我希望能够从每个name
元素中提取user
属性并将其存储在列表中。在这种情况下,我希望列表包含以下值:
我试过这个:
XElement documentRoot = XElement.Load(getUserRoles);
XmlNodeList nodes =
root.SelectNodes("/role/extradata/include/users");
foreach (XmlElement node in nodes)
{
log.Info("User in role : " + node.Value);
}
不幸的是,这不起作用。如何提取这些值并将其存储在列表中?
答案 0 :(得分:3)
首先,XML在这里有一个错误:
用户名=“问:”问:www \ sitename3“
其次,试试这个。
var xmlstring =
"<role name=\"olvers\" guid=\"ee81e26aeb7cd\" description=\"Used at\" isdynamic=\"false\"> <extradata> </extradata> <include> <users> <user name=\"Q:www\\sitename1\" /> <user name=\"Q:www\\sitename2\" /> <user name=\"Q:www\\sitename3\" /> </users> <groups /> <smartobjects /></include><exclude><users /><groups /><smartobjects /></exclude></role>";
var domdocument = new XmlDocument();
domdocument.LoadXml(xmlstring);
var sb = new StringBuilder();
foreach (XmlElement selectNode in domdocument.SelectNodes("//users/user"))
{
sb.Append(selectNode.Attributes["name"].Value);
}
答案 1 :(得分:1)
路径错了。如果您正在阅读根元素,那么应该是include/users/user
。
答案 2 :(得分:0)
using System.Xml.XPath;
var doc = XDocument.Parse(getUserRoles);
var names = doc.XPathSelectElements("/role/include/users/user/@name")
.Select(attribute => attribute.Value)
.ToList();