嗨我想从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)
{
}
}
答案 0 :(得分:1)
你应该能够通过
获得它user.Parent.Attribute("NAME").Value;
这适用于:
<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();
答案 1 :(得分:1)
似乎属性区分大小写。
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)
{
}
}
答案 2 :(得分:1)
以下代码应该适合您。
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;