Why use XML as a storage format? [duplicate]

2019-04-11 21:49发布

Possible Duplicate:
When is it OK to use an XML file to save information?

What's up with everything using XML as a storage format for configuration files such? I'm asking because [name retraced] framework has an XML configuration file to store database credentials, and the particular application that's built upon the framework has some menus stored as an XML fragment in a database... it's not like we'd share database credentials or or menu structure with others, or even data that would be consumed by multiple services. It's all internal/specific to this app. A coworker said that XML is an easily-readable format for humans... but I don't think that's true. password foobar123 in an INI file is easier for a human to read than <password>foobar123</password>. Then he said about parsing, but INI files have been around for ages so I'm sure there's a library or two for parsing them. I could see the logic behind using it as a data export method, because then whatever the app produces can be consumed by other services in a straightforward manner, but for internal stuff I just don't get it. Someone please enlighten me.

8条回答
爷、活的狠高调
2楼-- · 2019-04-11 22:30

I find it's because different technologies like different formats that complements their "style" of coding. For example, java tends to use XML because of it's ability to use namespaces and versioning to break up the data. Where as javascript tends to use JSON to store data due to it's simple/fast/easy-to-understand nature.

PHP doesn't have one standard encoding for storing data.

Regarding speed is required, it's best to store them as valid PHP using var_export to write them and require to read them. There are a number of frameworks that do something along these lines to make configure reading fast. As long as the files are decently small the opcode caching will keep any reads to these files very fast. Though there is no reason why you couldn't (and shouldn't) use XML, YAML, JSON if speed isn't your number one priority.

config.php

<?
return array( "db_name" => ..., "db_user" => ... );
?>

read-config.php

<?
$db_configure = require( "config.php" );
//do stuff with $db_configure
?>
查看更多
够拽才男人
3楼-- · 2019-04-11 22:31

The reasons as they should be:

  • interoperability (almost anything can talk XML, but in a closed system this it moot, up until the very day another application has to be able to read it)
  • validation (XSD etc.)
  • hierarchical

The actual reason:

  • The manager likes the buzzword & to claim 'it works with XML'
  • There were so many happy people claiming 'it works with XML' that actual developers came to think it was a good thing

Then again, formats like JSON, YAML, csv, or standard .ini all have their places.

查看更多
登录 后发表回答