When is it OK to use an XML file to save information?
What reason could there be for u开发者_运维知识库sing an XML to save information?
There could be lots of reasons: like any other file format, it has pros and cons:
Pros:
- .Net natively supports serializing your objects to xml, and deserializing them back again.
- It is more readable and descriptive to the human eye than a binary format or JSON
- It is easily validated against a schema to ensure it is in the correct format.
- It can be loaded and parsed with other tools.
- It is easily interchangeable with other platforms/languages, unlike the native .Net binary serialization format
- It can be transformed, and you can run xpath over it.
Cons:
- It is more verbose than either the native .Net binary serialization format, or JSON
- It doesn't store type information about the classes that were deserialized into xml, whereas a the native binary format does.
It's a portable, parsable standard.
So if you have data that needs to be read by several different programs (and possibly people) you could use XML.
It is also relatively easy to validate and transform (via XSLT) into other formats.
Obviously you could use other formats, but that doesn't stop you using XML.
It's probably a good idea to invert your question: when would it not be okay to use XML to save information?
When you only need to append data frequently, the canonical example being log files. XML would require you to parse the whole document and find the correct position for inserting in order not to break the well-formed structure
When you only need to query certain items in the file frequently. XML would probably not be efficient to randomly access parts of the file. This could probably be better handled with a format that stores the frequently accessed information at a well-know offset so that parsing the file is not required.
When storing non-hierarchical, sequential data there are usually better alternatives to XML. Think about image, audio or video file formats.
The standard line is "for human readable and computer readable data"
But other formats like JSON are less verbose and equally versatile.
We use it for saving our machine configuration files. We have a lot of machines in the field that get configured a number of different ways. We can use the DataContract or Xml serializer, which is easy to implement.
The benefit for us, is that we can easily diff these files to look at differences between the machines.
精彩评论