JavaScript. Intro to XML

Home » Tutorials » JavaScript » JavaScript. Intro to XML
Last lesson we discussed json. Today we consider XML – extended markup language
XML has similarities with HTML. Both languages are markup languages. But HTML is web page markup language, while XML is data structure markup language. XML may be pretty for display with XSLT.
XML сonsists of tags, but unlike html developer use own tags. In example below we describe books. So we can use tag for collection and tag for describing one book.

In xml we can add attribute. In code below it is birthday attribute.

XML string parse with DOMParser object. It has parseFromString method.
This method returns DOM object. You can get data from it exactly the same as html. XML hasn’t id and classes. That’s why it has the meaning to use getElementByTagName method.

XML file example

<?xml version="1.0" encoding="UTF-8"?>
<books>
    <book>
        <name>Евгений Онегин</name>
        <type>роман</type>
        <author birthday="06.06.1799">А.С.Пушкин</author>
    </book>

    <book>
        <name>Война и мир</name>
        <type>роман</type>
        <author birthday="06.06.1799">Л.Н.Толстой</author>
    </book>

    <book>
        <name>Я помню чудное мгновенье</name>
        <type>стихи</type>
        <author birthday="06.06.1799">А.С.Пушкин</author>
    </book>
</books>

Code lesson

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
    </head>
    <body>


    <script>

    var xmlStr = '<?xml version="1.0" encoding="UTF-8"?><books><book><name>Евгений Онегин</name><type>роман</type><author birthday="06.06.1799">А.С.Пушкин</author></book></books>';

    var parser = new DOMParser();
    xmlDoc = parser.parseFromString(xmlStr, "text/xml");
    console.log(xmlDoc.getElementsByTagName("name"));


    </script>

    </body>
</html>

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.

Pin It on Pinterest

Share This