XML по сравнению с файлами разделенного текста запятой

Псевдо переменную среды называют errorlevel хранилища код выхода:

echo Exit Code is %errorlevel%

кроме того, эти if команда имеет специальный синтаксис:

if errorlevel

См. if /? для деталей.

Пример

@echo off
my_nify_exe.exe
if errorlevel 1 (
   echo Failure Reason Given is %errorlevel%
   exit /b %errorlevel%
)

Предупреждение: Если Вы определите имя переменной среды errorlevel, [то 117] возвратит то значение а не код выхода. Используйте (set errorlevel=) для очистки переменной среды, предоставляя доступ к истинному значению errorlevel через %errorlevel% переменная среды.

11
задан Sasha Chedygov 17 July 2009 в 00:30
поделиться

12 ответов

Это не единственные два варианта, вы также можете использовать JSON или YAML , которые намного легче, чем xml.

В целом, если у вас есть простые табличные данные без множества специальных символов, CSV - неплохой выбор. Для структурированных данных рассмотрите возможность использования одного из других 3.

11
ответ дан 3 December 2019 в 00:56
поделиться

Advantages

A number of advantages XML has over CSV:

  • Hierarchical data organization
  • Automatic data validation (XML Schemas or DTDs)
  • Easily convert formats (using XSL)
  • Easy to identify relational structure
  • Can be used in combination with XML-RPC
  • Suitable for object persistence (marshalling)
  • Simplifies business-to-business communications
  • Helpful related technologies (XPath, DOM)
  • Tight integration with modern Web browsers
  • Extract, Transform, and Load (ETL) tools
  • Backwards file format compatibility (version attribute)
  • Digital signatures

It completely depends on the problem domain and what you are trying to solve.

Example

The last item is something that many people miss when writing web pages. Consider the situation where you have a large data store of songs. Songs have artists, albums, beats per minute, and so forth. You could export the data to XML, write a simple stylesheet to render the XML as XHTML, then point the browser at the XML page. The browser will render the XML as a web page.

You cannot do that with CSV.

Disadvantages

Joel Spolsky has a great article on why XML is a poor choice as a complex data store: it is slow. (Unlike a database, which can retrieve previous or next records with a single CPU instruction, traversing records in an XML document is much slower.) Arguably, this could be considered an optimization problem, resolved by waiting 18 months. Thus:

  • Slower to parse than other formats
  • Syntactical redundancy can detract from readability
  • Document bloat could affect storage costs
  • Cannot easily model overlapping (non-hierarchical) data structures
  • Poorly designed XML file formats are not uncommon (in my experience; citation needed)

Related Question

See also: Why Should I Use A Human Readable File Format.

16
ответ дан 3 December 2019 в 00:56
поделиться

XML поддерживает сложное, структурированное и иерархическое представление вещей. Это далеко не то, что можно просто сохранить в CSV.

Подумайте о сложном графе объектов в объектно-ориентированной среде. Его довольно легко сериализовать как XML-документ, но CSV не может справиться с этим.

6
ответ дан 3 December 2019 в 00:56
поделиться

Все зависит от того, что вам нужно делать. Если вам нужна более сложная структура данных, чем может дать простая «плоская» строчная структура. например, иерархические данные, тогда XML - отличный выбор.

4
ответ дан 3 December 2019 в 00:56
поделиться

Well XML is human readable and human editable. You can look at an XML file and know exactly what it is. A CSV file is human readable but you don't really know what each value means at all.

For example, if we're storing user accounts, which would you prefer?

<user>
    <username>ryeguy</username>
    <password>abc123</password>
    <regdate>3-4-08</regdate>
    <email>my@email.com</email>
</user>

OR

ryeguy,abc123,3-4-08,my@email.com

Of course, this is just an example, but imagine it with 30 fields or so!

Or worse yet, what if we make subfields?

<user>
    <username>ryeguy</username>
    <password>abc123</password>
    <regdate>3-4-08</regdate>
    <email>my@email.com</email>
    <posts>
        <post>
            <id>34</id>
            ....
        </post>
    </posts>
</user>

That would be a pain in the ass to put in a CSV. Soon you'd be making your own querying language.

4
ответ дан 3 December 2019 в 00:56
поделиться

CSV никогда не был стандартом. Тот же самый быстрый и грязный метод, который кучка людей придумала самостоятельно. Конечно, некоторые из этих людей были умнее других и понимали, что нужно избегать персонажей, а другие - нет. Даже MSSQL неправильно экспортирует CSV. Существует задокументированный ПРАВИЛЬНЫЙ способ создания XML, поэтому, если вы делаете это правильно, а чье-то приложение или что-то еще не принимает его, у вас будет некоторое влияние, когда вы скажете: «Это не моя вина».

2
ответ дан 3 December 2019 в 00:56
поделиться

The fact that XML is human readable does not mean that has been made with the idea of having it read (or even edited) directly by humans.

XML has a nice set of properties that make it a good choice for many cases, in particular when you have the human resources to deal with the additional burden that such properties inevitably bring in: validation, well defined standard, a lot of tools, a very flexible architecture, it maps nicely to a tree model, which is what many programs use. Its human readability is an added value that simplifies debugging (try to do debugging of a binary file...), inspection and small changes for trivial cases.

CSV on the other hand is easy, quick and linear, although many dialects exist, and parsing it well is far from trivial (and with the added problem that it looks trivial!). For most applications involving table of data, CSV is the perfect choice.

In general, however, there are cases of data representation you can solve with XML but you cannot solve with CSV (for example, a tree). On the other hand, any data that can be represented in CSV can also be represented in XML, although it's not guaranteed (and indeed is also verified) that it will be more efficient (in terms of space, ease of parsing etc). It's a matter of "degrees of freedom" of your format. XML has a higher value of degree of freedom. CSV is lower. The hype behind XML is also relative to this fact.

Don't fall victim of the hammer syndrome: when you have a hammer (XML), everything looks like a nail (something that you have to solve with XML). Reality is much different and nuanced. XML is cool, but it's not the answer to any problem.

3
ответ дан 3 December 2019 в 00:56
поделиться

XML будет описывать контент, а также содержит массу вспомогательных библиотек на разных языках ... но он может быть раздутым. Если принимающая сторона csv знает о компоновке и она табличная, я не вижу в ней ничего плохого.

2
ответ дан 3 December 2019 в 00:56
поделиться

Xml can be validated against a contract (schema or DTD).

1
ответ дан 3 December 2019 в 00:56
поделиться

XML also has complimentary technologies surrounding it: XmlDom, XPath, XSLT, XSD, Xml Schemas

1
ответ дан 3 December 2019 в 00:56
поделиться

Among the reasons you may prefer XML over CSV (depends on the task at hand of course): * Almost all platforms and languages have existing libraries for reading, writing, parsing, and manipulating XML. * XML has well-defined rules for encoding all characters. CSV has ambiguities such as how to encode commas that are part of the data. * XML supports a variety of data shapes (like hierarchical) where as CSV is most useful when the data looks like a table (rows and columns).

1
ответ дан 3 December 2019 в 00:56
поделиться

Мне нравится думать об основных различиях в этом случае, поскольку XML основан на ДЕРЕВЕ, а CSV основан на ТАБЛИЦАх.

То есть вы можете вкладывать и повторно вкладывать и опускать и, как правило, создавать сложную структуру ДЕРЕВО в XML, тогда как вы можете создавать только простые 2D-таблицы в CSV.

1
ответ дан 3 December 2019 в 00:56
поделиться
Другие вопросы по тегам:

Похожие вопросы: