Parsing XML data in C# and show into ListBox

前端 未结 4 2071
灰色年华
灰色年华 2020-12-11 08:36

I am trying to parse a XML file in C# using Visual Studio and show the data in a ListBox, but I don\'t know how to parse it when I\'m dealing with a nested XML file.

4条回答
  •  感情败类
    2020-12-11 08:58

    You can get LikedPerson node and get it's name/age like you do now. In order to avoid code duplication, you can create a method, which takes XmlNode, parses it recursively and returns a Person. But the better way is to use XmlSerializer

    foreach (XmlNode node in doc.DocumentElement) 
    {
        string name = node.Attributes[0].Value;
        int age = int.Parse(node["Age"].InnerText);
        bool isMale = bool.Parse(node["IsMale"].InnerText);
    
        var likedPerson = node.SelectSingleNode("LikedPerson");
    
        if (likedPerson != null){
            string name = likedPerson.Attributes[0].Value;
            //age, gender, etc.        
        }        
    }
    

提交回复
热议问题