简体   繁体   中英

Get all the attribute values of nodes from an XML File

I have created an xml file like below

<Engagements>
    <User name ="jjjj">
        <Engagement id="1111"/>
    </User>
    <User name ="kkkk">
        <Engagement id="2222"/>
    </User>
</Engagements>

I need to get all the id values from all of the Engagement nodes.

This is what I currently have:

public static void ParseXml(XmlDocument xmlFile) 
{
  XmlNodeList nodes = xmlFile.SelectNodes("//Engagement"); 
  foreach (XmlNode node in nodes) 
  { 
    // What goes here?
  } 
} 

Use LINQ to 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();

You can use following code to get all ids in a list

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(yourxmlStringInput);
var engagements = xmlDoc.GetElementsByTagName("Engagement");
var ids = (from engagement in engagements 
          select engagement.Attributes["id"].Value).ToList();

If those other great answers don't do it for you, maybe showing you the answer in the same context you are stuck in:

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.
  } 
}

If you only want the attribute portion of the nodes that have an id attribute you can restrict your XPath query by specifying that you require that attribute and select it like so:

XmlNodeList nodes = xmlFile.SelectNodes("//Engagement[@id]/@id");

Each node returned with this query will be an ID attribute node, so you can get the value in your loop using 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);
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM