2017年3月12日日曜日

javascript : XML parser for javascript

The DOM defines for accessing and manipulating documents. DOM -- Document Object Model -- is the API for HTML and XML. This document will explain you how to get XML elements using javascript. All XML elements can be accessed through the XML DOM. The XML DOM provides you a standard way to get, add, modigy and delete XML elements.

This code get the text content of the first element in an XML document.

Sample XML

<?xml version="1.0">
<catalog>
    <item>
        <code>I00001</code>
        <name>Item Name No.1</name>
        <cost>100</cost>
        <price>200</price>
    </item>
    <item>        
        <code>I00002</code>
        <name>Item Name No.2</name>
        <cost>300</cost>
        <price>400</price>
    </item>
</catalog>

Example

function xmlparser(sampleXML) {

    // Parse XML
    var parser = new DOMParser();
    var dom = parser.parseFromString(sampleXML, "text/xml");

    // Set XML to Text
    document.getElementById("code").value = 
         dom.getElementsByTagName("code")[0].textContent;
    document.getElementById("name").value = 
         dom.getElementsByTagName("name")[0].textContent;
    document.getElementById("cost").value = 
         dom.getElementsByTagName("cost")[0].textContent;
    document.getElementById("price").value = 
         dom.getElementsByTagName("price")[0].textContent;
}

You can get first <tag> elements. So, this code will give you "I000001".

dom.getElementsByTagName("code")[0].textContent;

If you want to get second elements, you should try this code.

dom.getElementsByTagName("code")[1].textContent;