All type of food available

Parsing and serializing XML

At times, you may need to parse XML content and convert it into a DOM tree, or, conversely, serialize an existing DOM tree into XML. In this article, we’ll look at the objects provided by the web platform to make the common tasks of serializing and parsing XML easy.

Serializes DOM trees, converting them into strings containing XML.

Constructs a DOM tree by parsing a string containing XML, returning a XMLDocument or Document as appropriate based on the input data.

Loads content from a URL; XML content is returned as an XML Document object with a DOM tree built from the XML itself.

A technology for creating strings that contain addresses for specific portions of an XML document, and locating XML nodes based on those addresses.

Creating an XML document

Using one of the following approaches to create an XML document (which is an instance of Document ).

Parsing strings into DOM trees

This example converts an XML fragment in a string into a DOM tree using a DOMParser :

const xmlStr = 'hey!'; const parser = new DOMParser(); const doc = parser.parseFromString(xmlStr, "application/xml"); // print the name of the root element or error message const errorNode = doc.querySelector("parsererror"); if (errorNode)  console.log("error while parsing"); > else  console.log(doc.documentElement.nodeName); > 

Parsing URL-addressable resources into DOM trees

Using XMLHttpRequest

Here is sample code that reads and parses a URL-addressable XML file into a DOM tree:

const xhr = new XMLHttpRequest(); xhr.onload = () =>  dump(xhr.responseXML.documentElement.nodeName); >; xhr.onerror = () =>  dump("Error while getting XML."); >; xhr.open("GET", "example.xml"); xhr.responseType = "document"; xhr.send(); 

The value in the xhr object’s responseXML field is a Document constructed by parsing the XML.

If the document is HTML, the code shown above will return a Document . If the document is XML, the resulting object is actually a XMLDocument . The two types are essentially the same; the difference is largely historical, although differentiating has some practical benefits as well.

Note: There is in fact an HTMLDocument interface as well, but it is not necessarily an independent type. In some browsers it is, while in others it is an alias for the Document interface.

Serializing an XML document

Given a Document , you can serialize the document’s DOM tree back into XML using the XMLSerializer.serializeToString() method.

Use the following approaches to serialize the contents of the XML document you created in the previous section.

Serializing DOM trees to strings

First, create a DOM tree as described in How to Create a DOM tree. Alternatively, use a DOM tree obtained from XMLHttpRequest .

To serialize the DOM tree doc into XML text, call XMLSerializer.serializeToString() :

const serializer = new XMLSerializer(); const xmlStr = serializer.serializeToString(doc); 

Serializing HTML documents

If the DOM you have is an HTML document, you can serialize using serializeToString() , but there is a simpler option: just use the Element.innerHTML property (if you want just the descendants of the specified node) or the Element.outerHTML property if you want the node and all its descendants.

const docInnerHtml = document.documentElement.innerHTML; 

As a result, docInnerHtml is a string containing the HTML of the contents of the document; that is, the element’s contents.

You can get HTML corresponding to the and its descendants with this code:

const docOuterHtml = document.documentElement.outerHTML; 

See also

Found a content problem with this page?

This page was last modified on Jul 4, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

XML Parsing in JavaScript

XML Parsing in JavaScript

XML parsing in JavaScript is defined as it is one kind of package or library of the software which provides an interface for the client applications to work with an XML document and it is used in JavaScript to transform the XML document into readable form, nowadays in many browsers, the XML parser is already available that is in-built which can able to check the format of the XML document and to validate it, we can say that the main purpose of the XML parser is to transform the XML document into the code which can be readable by human.

Web development, programming languages, Software testing & others

What is XML parsing in JavaScript?

Many browsers have an in-built XML parser that can transform the document of XML into human-readable formats, we can also say that the XML parser is a software package that can interact with an XML document to check the format of the document and to validate it through the client applications because to manipulate data which is comes from the XML file is quite hard. The XML parser works between the client application and the XML document and the work of it is to validate the document which passing through it and it is mainly designed to the document of XML and it has programs to read the XML document. The XML parsing is working with all browsers to read and write it and it has a simple API. As it has a DOM parser and the SAX parser which can help to parse the text, parse the string, and also parse the file.

A long time ago the XML parser has been added to the browsers and the JavaScript need to add a new parser for other languages so that for the other languages it has to define the data structure which allows serialization of the data.

There are two main parsers are available in JavaScript,

DOM (Document Object Model) parser

The DOM parser contains all the information of an XML document in the form of the XML document object, the API is very simple and it is used to performs read and write both operations, and it is implemented by a DOM parser and it can create like a tree structure and it is advantageous when we need to access the document in a random manner but it has the disadvantage that it is slower than the other parsers and it consumes more memory because the complete document it needs to load into the memory so that it required more memory.

SAX (Simple API for XML)parser

The Simple API for XML is used to implement the API, and it is event-based, it does not create any internal structure. The clients of it do not have any idea about which method can call it only know to override the method and place their own code inside it. The advantage of this API is that it has a simple API and the memory of it is very efficient also it works with huge documents which are very fast but it is disadvantageous about the API of it is less intuitive because it is event-based and it breaks the data into the pieces so that the clients do not know the full information about it.

Examples

XML parsing in JavaScript:

Example #1

     

3

In the above code, we have seen an example of parsing a text into an XML document object and try to extract information from it with JavaScript, we take an example of a food shop with a title and we take text, parser, and the XML document, by using the method we have to parse our text through the XML document object and output of it we have given above.

Example #2

   

Important message

To:
from:
Message:

XML Parsing in JavaScript 1

In this example, we have extracted the XML string by using DOM parser to print message by using text it creates a tree structure so that the text or the string we have written will show in the output, in that we try to show the message for mother so for that we have called the parser method and the output for reference is given above.

Parsing a String to XML (coding):

In this section we will see how to parse an XML string by using JavaScript, in this example, we will take a string containing XML and try to parse it into an object of the XML document so that object will allows reading and manipulating it easily.

Let us see an example of JavaScript,

var xmlString = '2021-10-05, 10:00:00 Interview Interview is on XML-Parser in JavaScript '; var domParser = new DOMParser(); var xmlDocument = domParser.parseFromString(xmlString,"text/xml"); console.log(xmlDocument);

XML Parsing in JavaScript

In the above code, we have created a basic XML file, in this example, we take XML to constitute a reminder and we have created an instance DOMParser, by using the method we try to parse the XML string into an object of an XML document and also we did it by taking another parameter mimeType to text/XML, so we go through the new XML document instance to the browser console.

Conclusion

In this article we have seen the introduction of XML parser in JavaScript with type and features, parsing the text and the string with explanation, also describe the syntax of how to parse a string into an XML document object, this article will help to understand the concept of XML parser in JavaScript.

This is a guide to XML Parsing in JavaScript. Here we discuss the definition, What is XML parsing in JavaScript? respectively. You may also have a look at the following articles to learn more –

89+ Hours of HD Videos
13 Courses
3 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5

97+ Hours of HD Videos
15 Courses
12 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5

XML Course Bundle — 11 Courses in 1
45+ Hours of HD Videos
11 Courses
Verifiable Certificate of Completion
Lifetime Access
4.5

Источник

Читайте также:  Bitrix urlrewrite php запрещен
Оцените статью