Get XML Attributes By Tag Name - CSharp System.Xml

CSharp examples for System.Xml:XML Attribute

Description

Get XML Attributes By Tag Name

Demo Code


using System.Xml;
using System.Collections.Generic;
using System;//from  w  w w  .j a  va2s.  c  om

public class Main{
        public static Dictionary<string, Dictionary<string, string>> GetAttributesByTagName(XmlDocument xmlFile, string tagName, string[] attributes) {
            Dictionary<string, Dictionary<string, string>> dictionary = new Dictionary<string, Dictionary<string, string>>();
            XmlNodeList nodeList = GetElementsByTagName(xmlFile, tagName);
            for (int i = 0; i < nodeList.Count; i++) {
                Dictionary<string, string> tmpDictionary = new Dictionary<string, string>();
                for (int j = 0; j < attributes.Length; j++) {
                    XmlAttribute currentAttribute = nodeList[i].Attributes[attributes[j]];
                    tmpDictionary.Add(currentAttribute.Name, (string.IsNullOrEmpty(currentAttribute.Value)) ? string.Empty : currentAttribute.Value);
                }
                dictionary.Add(nodeList[i].Name, tmpDictionary);
            }
            return dictionary;
        }
        public static Dictionary<string, List<string>> GetAttributesByTagName(string xmlFilePath, string tagName, string[] attributes) {
            Dictionary<string, List<string>> dictionary = new Dictionary<string, List<string>>();
            XmlNodeList nodeList = GetElementsByTagName(xmlFilePath, tagName);
            for (int i = 0; i < nodeList.Count; i++) {
                List<string> list = new List<string>();
                for (int j = 0; j < attributes.Length; j++) {
                    string currentValue = nodeList[i].Attributes[attributes[j]].Value;
                    list.Add((string.IsNullOrEmpty(currentValue)) ? string.Empty : currentValue);
                }
                dictionary.Add(nodeList[i].Value, list);
            }
            return dictionary;
        }
}

Related Tutorials