LINQ to read XML

前端 未结 5 1929
逝去的感伤
逝去的感伤 2020-11-22 00:47

I got this XML file:


    
        
        
             


        
5条回答
  •  抹茶落季
    2020-11-22 01:37

    Or, if you want a more general approach - i.e. for nesting up to "levelN":

    void Main()
    {
        XElement rootElement = XElement.Load(@"c:\events\test.xml");
    
        Console.WriteLine(GetOutline(0, rootElement));  
    }
    
    private string GetOutline(int indentLevel, XElement element)
    {
        StringBuilder result = new StringBuilder();
    
        if (element.Attribute("name") != null)
        {
            result = result.AppendLine(new string(' ', indentLevel * 2) + element.Attribute("name").Value);
        }
    
        foreach (XElement childElement in element.Elements())
        {
            result.Append(GetOutline(indentLevel + 1, childElement));
        }
    
        return result.ToString();
    }
    

提交回复
热议问题