递归获取XML元素
看到的一道题,用递归获取XML元素....
static void Main(string[] args) { string xmlContent = @"<FileSystem> <DriverC> <Dir DirName='MSDOS622'> <File FileName ='Command.com' ></File> </Dir> <File FileName ='MSDOS.SYS' ></File> <File FileName ='IO.SYS' ></File> </DriverC> <DriverC> <Dir> <File FileName ='DriverC.com' ></File> </Dir> <File FileName ='DriverC.SYS' ></File> <File FileName ='DriverCIO.SYS' ></File> </DriverC> </FileSystem>"; var parentElement = XElement.Parse(xmlContent); var elements = FindElements(parentElement.Elements(), "File"); } public static IList<XElement> FindElements(IEnumerable<XElement> elements, string elementName) { if(elements==null||elements.Count()==0 ||string.IsNullOrWhiteSpace(elementName)) { return new List<XElement>(); } var selectedElements = new List<XElement>(); foreach (var element in elements) { if (element.HasElements) { selectedElements.AddRange(FindElements(element.Elements(), elementName)); } else { if (string.Equals(element.Name.LocalName, elementName)) { selectedElements.Add(element); } } } return selectedElements; }