2

Дано: Есть большой xml файл.

Вопрос: Как вывести элементы и атрибуты, если структура дерева не известна?

6
  • Насколько большой? Считать весь файл в XDocument не выйдет?
    – VladD
    17 июн 2016 в 8:45
  • 410 строчек, я даже не знаю , я новичёк 17 июн 2016 в 8:48
  • 410 — это очень маленький файл. Понял, напишу, как доберусь до компьютера.
    – VladD
    17 июн 2016 в 8:50
  • буду очень благодарен 17 июн 2016 в 8:52
  • Готово, смотрите.
    – VladD
    17 июн 2016 в 12:56

1 ответ 1

1

Вот вам пример:

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}>");
    }
}

Для стандартного Майкрософтовского тестового примера выдаёт:

* 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]

и т. д.

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.