It is given: There is a big xml file.

Question: How to display elements and attributes if the tree structure is not known?

  • How big? Read the entire file in the XDocument will not work? - VladD
  • 410 lines, I don’t even know, I'm new - Alexander
  • 410 is a very small file. Understood, I will write how to get to the computer. - VladD
  • I will be very grateful - Alexander
  • Done, look. - VladD

1 answer 1

Here is an example:

 class Program { static void Main(string[] args) { var doc = XDocument.Load(<тут путь к вашему XML>); DisplayElement(doc.Document.Root); } static void DisplayElement(XElement e, int indentLevel = 0) { DisplayNameAndAttributes(e, indentLevel); foreach (var child in e.Nodes()) { var childElement = child as XElement; if (childElement != null) DisplayElement(childElement, indentLevel + 1); var contentText = child as XText; if (contentText != null) DisplayContent(contentText, indentLevel + 1); // тут можно проверять другие типы узлов, например, комментарии } } static void DisplayNameAndAttributes(XElement e, int indentLevel) { var indentString = new string(' ', 2 * indentLevel); Console.Write($"{indentString}* {e.Name}"); if (e.HasAttributes) { Console.Write(" ["); bool first = true; foreach (var attr in e.Attributes()) { if (!first) Console.Write(", "); first = false; Console.Write($"{attr.Name} = {attr.Value}"); } Console.Write(']'); } Console.WriteLine(); } static void DisplayContent(XText contentText, int indentLevel) { var indentString = new string(' ', 2 * indentLevel); var text = contentText.Value; Console.WriteLine($"{indentString}<text content: {text}>"); } } 

For a standard Microsoft test case, it produces:

 * catalog * book [id = bk101] * author <text content: Gambardella, Matthew> * title <text content: XML Developer's Guide> * genre <text content: Computer> * price <text content: 44.95> * publish_date <text content: 2000-10-01> * description <text content: An in-depth look at creating applications with XML.> * book [id = bk102] * author <text content: Ralls, Kim> * title <text content: Midnight Rain> * genre <text content: Fantasy> * price <text content: 5.95> * publish_date <text content: 2000-12-16> * description <text content: A former architect battles corporate zombies, an evil sorceress, and her own childhood to become queen of the world.> * book [id = bk103] 

etc.