Java Reference
In-Depth Information
Next, opening and closing tags surround both the first and last name. Naturally, there needs to be
some way to organize that data, but yet, this XML uses 55 bytes to denote the first name, last name,
and the age.
Another of XML's issues is the code necessary for reading, parsing, and generating XML data. Yes,
most modern programming languages can handle XML, but it requires a lot of code—code that
usually has to be rewritten for specific XML formats. For example, the following code is one way
you could read the previous XML and parse it into an object called person :
var personElement = document.querySelector("person");
var firstName = personElement.querySelector("firstName").innerHTML;
var lastName = personElement.querySelector("lastName").innerHTML;
var age = personElement.querySelector("age").innerHTML;
var person = {
firstName : firstName,
lastName: lastName,
age: age
};
This code demonstrates a straightforward approach to parsing the John Doe XML. It first retrieves
the <person/> element using document.querySelector() . It then retrieves the <firstName/> ,
<lastName/> , and <age/> elements and stores their respective contents in the firstName , lastName ,
and age variables. Finally, it creates the person object and assigns the appropriate data to its
properties. This code isn't complex, but as you might suspect, it wouldn't work for XML‐formatted
data with different element names and structures. Naturally, documents with more complex
structures require much more code.
But parsing XML into a JavaScript object is only half of the story. Before you can send data from
JavaScript to the server, you have to serialize the JavaScript object. Serializing a JavaScript object
to XML‐formatted data is not a trivial task. Like parsing, the same code usually doesn't work for
different data structures. Plus, developers must ensure their generated XML data is well‐formed.
Around 2007 and 2008, the web community thankfully adopted a different data format for storing
and transmitting JavaScript data.
Json
In 2006, Douglas Crockford wrote the JavaScript Object Notation specification. JSON is a subset
of the JavaScript language, and it uses several of JavaScript's syntactical patterns for organizing and
structuring data. As such, it is does a very good job of representing objects and their data (it's so
good that other languages use JSON, too). It's extremely easy to parse JSON into JavaScript objects
and to serialize objects into JSON. In today's modern browsers, it only takes one line of code!
As you soon see, JSON looks a lot like JavaScript's object and array literals. It's easy to confuse
JSON and JavaScript as being the same thing, but it's important to understand the difference
between the two. JavaScript is a programming language; JSON is a data format.
JSON lets you represent three types of data: simple values, objects, and arrays.
 
Search WWH ::




Custom Search