I had to write some code for an interview, to print out the name attribute of each node. I started off going in the wrong direction, so I didn't get to finish. I wanted to finish writing the code, so I created my console app similar to what they had a button event doing. Please let me know what you think of the code and what I can do better.
class XMLRecursionReader { private StringBuilder _outputString = new StringBuilder(); private XmlNode _root; public XMLRecursionReader(XmlDocument xDoc) { _root = xDoc.ChildNodes[1]; } public string ReturnNameAsString (XmlNode node) { return node.Attributes["name"].InnerXml.ToString(); } public void buildString (XmlNode node) { _outputString.AppendLine(ReturnNameAsString(node)); if (node.HasChildNodes) { foreach (XmlNode childNode in node.ChildNodes) { buildString(childNode); } } } public void PrintOutput () { buildString(_root); Console.WriteLine(_outputString.ToString()); Console.ReadLine(); } }
similar sample to what I was coding against. but the code needed to be generic and able to go as deep as necessary depending on the document that was fed in, but the structure is always going to be similar to this.
<?xml version="1.0" encoding="UTF-8"?> <report name="ReportName"> <agency name="agency1"> <office name="office1"></office> <office name="office2"></office> <office name="office3"></office> </agency> <agency name="agency2"> <office name="office1"> <agent name="agent Amy"></agent> <address name="address line"></address> </office> <office name="office2"></office> <office name="office3"></office> </agency> <agency name="agency3"> <office name="office1"> <agent name="agent Bettie"> <subagent name="sub-agent bob"> <phone name="456-789-1230"></phone> </subagent> <subagent name="sub-agent billy"></subagent> </agent> <address name="address line"> <faxnumber name="1234567890"></faxnumber> </address> </office> <office name="office2"></office> <office name="office3"></office> </agency> </report>