![](/img/trans.png)
[英]Get all the attribute values by attribute name from XML file using Linq to XML
[英]Get all the attribute values of nodes from an XML File
我已经创建了一个xml文件,如下所示
<Engagements>
<User name ="jjjj">
<Engagement id="1111"/>
</User>
<User name ="kkkk">
<Engagement id="2222"/>
</User>
</Engagements>
我需要从所有“ Engagement
节点获取所有id值。
这是我目前拥有的:
public static void ParseXml(XmlDocument xmlFile)
{
XmlNodeList nodes = xmlFile.SelectNodes("//Engagement");
foreach (XmlNode node in nodes)
{
// What goes here?
}
}
使用LINQ到XML:
XDocument doc = XDocument.Parse(xml);
var ids = doc.Descendants("Engagement").Attributes("id").Select(x => x.Value);
foreach (var id in ids)
Console.WriteLine(id);
var xmlString = "..."; // <--- your xml here
var xml = new XmlDocument();
xml.LoadXml(xmlString);
var xnList = xml.SelectNodes("/Engagements/User");
var test = "";
if (xnList != null)
foreach (XmlNode xn in xnList)
{
if (xn.Attributes != null)
{
if (xn.Attributes[0].Value == "kkkk")
{
if (xn.FirstChild.Attributes != null)
{
var xmlElement = xn.FirstChild.Attributes[0].Value;
if (xmlElement != null)
{
test = xmlElement;
}
}
}
}
}
Console.WriteLine(test);
Console.Read();
您可以使用以下代码获取列表中的所有ID
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(yourxmlStringInput);
var engagements = xmlDoc.GetElementsByTagName("Engagement");
var ids = (from engagement in engagements
select engagement.Attributes["id"].Value).ToList();
如果这些其他好的答案对您没有帮助,也许可以在您遇到的相同情况下向您显示答案:
public static void ParseXml(XmlDocument xmlFile)
{
XmlNodeList nodes = xmlFile.SelectNodes("//Engagement");
foreach (XmlNode node in nodes)
{
string id = node.Attributes["id"].InnerText;
// Do whatever you need to with each ID here.
}
}
如果只希望具有id
属性的节点的属性部分,则可以通过指定需要该属性并选择它来限制XPath查询 ,如下所示:
XmlNodeList nodes = xmlFile.SelectNodes("//Engagement[@id]/@id");
该查询返回的每个节点都是一个ID属性节点,因此您可以使用node.Value
在循环中获取值。
var xmlString =“”;
var xml = new XmlDocument();
xml.LoadXml(xmlString);
foreach (XmlNode node in xml.SelectNodes("//Engagement[@id]"))
{
Console.WriteLine(node.Attributes["id"].Value);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.