如果我有子节点的属性名,我如何获得parentnode属性名
本文关键字:属性 何获得 parentnode 如果 子节点 | 更新日期: 2023-09-27 18:16:27
嗨,我想从xml中获得up节点。例如这里的xml结构…
<feature name="mod1">
<user name="user1"></user>
<user name="user2"></user>
<user name="user3"></user>
</feature>
我有在我的应用程序的用户名,我想比节点功能名称属性。
XmlReader reader = XmlReader.Create(new StringReader(xml));
XElement doc = XElement.Load(reader);
int counter = 0;
foreach (XElement user in doc.Descendants("USER"))
{
try
{
row = tb.NewRow();
row["ID"] = counter++;
row["Name"] = user.Attribute("NAME").Value;
row["Host"] = user.Attribute("HOST").Value;
row["Used_Licenses"] = user.Attribute("USED_LICENSES").Value;
row["Checkout_Time"] = user.Attribute("CHECKOUT_TIME").Value;
row["Modul"] = user.Parent.Attribute("NAME").Value; //don't work :(
tb.Rows.Add(row);
}
catch (Exception)
{
}
}
你应该能够得到它
user.Parent.Attribute("NAME").Value;
this Works with:
<LM-X STAT_VERSION="3.32">
<LICENSE_PATH >
<FEATURE NAME="GlobalZoneEU" >
<USER NAME="SYSTEM" HOST="LRV171" IP="172.16.11.115" USED_LICENSES="2000" LOGIN_TIME="2013-04-17 12:42" CHECKOUT_TIME="2013-04-17 12:42" SHARE_CUSTOM="hweuser:172.16.11.115"/>
<USER NAME="pbsadmin" HOST="SERV11" IP="172.16.11.115" USED_LICENSES="720" LOGIN_TIME="2013-04-17 12:44" CHECKOUT_TIME="2013-04-17 12:44" SHARE_CUSTOM="pbsadmin:LWSERV171:1592_40960072_1356792762_826820"/>
</FEATURE>
</LICENSE_PATH>
</LM-X>
编辑
根据用户名获取功能名称:
var featureNames = xDoc.Descendants("USER")
.Where(x => x.Attribute("NAME").Value == <your input>)
.Select(x => x.Parent.Attribute("NAME").Value);
var firstFeatureName = featureNames.FirstOrDefault();
似乎属性是区分大小写的。
XmlReader reader = XmlReader.Create(''File Path);
XElement doc = XElement.Load(reader);
int counter = 0;
foreach (XElement user in doc.Descendants("USER"))
{
try
{
string node = user.Parent.Attribute("NAME").Value; //Working - Returning 'GlobalZoneEU'
}
catch (Exception)
{
}
}
下面的代码应该可以为您工作。
string xml = "<feature name='"mod1'">";
xml += "<user name='"user1'"> </user>";
xml += "<user name='"user2'"> </user> ";
xml += "<user name='"user3'"></user>";
xml += "</feature>";
XmlDocument xdoc=new XmlDocument();
xdoc.LoadXml(xml);
XDocument mydoc = XDocument.Parse(xdoc.OuterXml);
var result = mydoc.Elements("feature").Where(parent =>
parent.Elements("user").Any(child =>
child.Attribute("name").Value == "user2"));
,不要忘记包括使用System.Xml;使用System.Xml.Linq;