Populating dropdown from the XML in C#

后端 未结 5 2117
花落未央
花落未央 2021-01-06 06:00

I have got below xml format with me and I am using .NET 2.0.



  

        
5条回答
  •  北海茫月
    2021-01-06 06:11

    You could try following code, I would rather go for Xpath because it is more easier to read. DocumentLoader class, it loads content from string or any stream that has a valid xml content.

    public class DocumentLoader
        {
            private readonly string content;
            public  DocumentLoader(Stream stream):this(new StreamReader(stream).ReadToEnd())
            {
    
            }
            public DocumentLoader(string content)
            {
                this.content = content;
    
            }
            public KeyValuePair[] GetNames()
        {
            List> names=new List>();
            XmlDocument document=new XmlDocument();
            document.LoadXml(this.content);
            XmlNodeList xmlNodeList = document.SelectNodes("//publication");
            if(xmlNodeList!=null)
            {
                foreach (XmlNode node in xmlNodeList)
                {
                    string key = node.InnerText;
                   string value = "";
                    if (node.Attributes != null)
                    {
                        value = node.Attributes["tcmid"].Value;
                    }
                    names.Add(new KeyValuePair(key,value));
                }
            }
            return names.ToArray();
        }
        }
    

    Just a test code.

    public class DocumentLoaderTest
    {
        public void Test()
        {
            DocumentLoader loader = new DocumentLoader(File.Open("D:\\sampleSource.xml", FileMode.Open));
            //now names contains the value of the name element 
            List>names=loader.GetNames();
        }
    }
    

    Updated to get Name element and tcmid attribute

提交回复
热议问题