Read XML File in C# with same node name

2850 views c#
2

I need to read a XML file that has nodes with the same name. Can't figure how to accomplish the task. I've got a class of Person which contains two fields:

  1. PersonID
  2. HubbyList - List of hubbies object

XML:

<group>
  <person>
    <id>1</id>
    <hubby>
      <id>1</id>
    </hubby>
    <hubby>
      <id>2</id>
    </hubby>
    <hubby>
      <id>3</id>
    </hubby>
    <hubby>
      <id>4</id>
    </hubby>
  </person>
  <person>
    <id>2</id>
    <hubby>
      <id>1</id>
    </hubby>
    <hubby>
      <id>2</id>
    </hubby>
  </person>
</group>

answered question

What is your current code?

Welcome to Stack Overflow. Could you show how far you've got? Are you using LINQ to XML for example? You could find each person element with doc.Root.Elements("person") and the hubby elements within each person element with person.Elements("hubby")...

1 Answer

4

This is the method that will read your hubby nodes and make a list of objects and insert it one by one.

  XmlDocument xml = new XmlDocument();
    xml.LoadXml(myXmlString); // suppose that myXmlString contains "<group>...</group>"
    List<MyList> infos = new List<MyList>();
    XmlNodeList xnList = xml.SelectNodes("/group/person/hubby");
    foreach (XmlNode xn in xnList)
    {
      Info info = new Info();
      info = xn["hubby"].InnerText;
      info.Add(info);
    }

posted this

Have an answer?

JD

Please login first before posting an answer.