简体   繁体   中英

What is the difference between XML document & XML string?

Is there any content difference between the data?

Perhaps a document may have additional metadata like author, last date edited, etc.?

I'm trying to understand why the domparser example at w3 schools has two completely different methods for loading an xml string vs an xml document.

For example say both sources contained <book><page1>Hello World!</page1></book> .

First method offered loads the js object xmlDoc using XMLHttpRequest() and responseXML, the second uses DOMParser() and parseFromString()

How would the JS objects created by each method differ from one another?

The result of both ways is an object representing a xml structure.

The first way is loading (and parsing) a xml document from a remote location using an XMLHttpRequest.

The second way assumes you already have xml content in your script (stored in a variable, doesn't matter how it got there). The xml string content will then be parsed to an object so you can easily perform operations on the xml data (which isn't possible on the string)

You can work with the resulting xml object like this:

var p = new DOMParser()
xmldoc = p.parseFromString('<book><page1>Hello World!</page1></book>', 'text/xml')

xmldoc.childNodes.item(0) // the <book> tag
xmldoc.childNodes.item(0).childNodes.item(0) // the <page1> tag
xmldoc.childNodes.item(0).childNodes.item(0).textContent // "Hello World!"

The first example builds an XML tree from an XML file you still have to load. It uses the XMLHttpRequest for that, which loads an XML file from a webserver and automatically parses it to create an XML document.

The second example builds an XML tree from a string you already have which contains XML code.

xml documents should begin with an xml declaration:

http://www.w3.org/TR/REC-xml/#sec-prolog-dtd

This declaration might not be present in the xml string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM