Mohanavel T
Mohanavel T

Reputation: 391

Parsing XML Schema with XML Parser in JavaScript

I have the following schema in which i have to find each element name listed.

> <?xml version='1.0' encoding='UTF-8' ?> <xs:schema
> xmlns:xs='http://www.w3.org/2001/XMLSchema'>
> 
> 
> <xs:sequence> <xs:element name='name' type='xs:string'/> <xs:element
> name='address' type='xs:string'/> <xs:element name='city'
> type='xs:string'/> <xs:element name='country' type='xs:string'/>
> </xs:sequence>
> 
> </xs:schema>
  1. Name
  2. Street
  3. city
  4. state
  5. country

I tried with this code:

var app = angular.module('httpApp', []);

    app.controller('httpController', function ($scope, $http) {

        var xmlm="<?xml version='1.0' encoding='UTF-8' ?><xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'><xs:sequence><xs:element name='name' type='xs:string'/><xs:element name='address' type='xs:string'/><xs:element name='city' type='xs:string'/><xs:element name='country' type='xs:string'/></xs:sequence></xs:schema>";

                //var x2js = new X2JS();
                $scope.data=xmlm;
                //var aftCnv = x2js.xml_str2json(xmlm);

                //$scope.jsonic=aftCnv;

        xmlDoc = $.parseXML( xmlm ),
        $xml = $( xmlDoc ),
        $name = $xml.find( "xs:sequence" );
        $scope.data=$name.text();
        $( "#1" ).append( $name.text() );

I get neither errors on the console or the output. The Page is empty.

Upvotes: 1

Views: 3754

Answers (1)

Ali Mamedov
Ali Mamedov

Reputation: 5256

You can use this jQuery XML to JSON Plugin.

Sample (with your xml string):

<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.3.min.js"></script>
<script type="text/javascript" src="https://jquery-xml2json-plugin.googlecode.com/svn/trunk/jquery.xml2json.js"></script>
<script type="text/javascript">
    $(function() {

        var 
            xmlm,
            json,
            elements;

        xmlm =
            "<?xml version='1.0' encoding='UTF-8' ?>" + 
            "<xs:schema" + 
            "   xmlns:xs='http://www.w3.org/2001/XMLSchema'>" + 
            "   <xs:sequence>" + 
            "       <xs:element name='name' type='xs:string'/>" + 
            "       <xs:element name='address' type='xs:string'/>" + 
            "       <xs:element name='city' type='xs:string'/>" + 
            "       <xs:element name='country' type='xs:string'/>" + 
            "   </xs:sequence>" + 
            "</xs:schema>";

        json = $.xml2json(xmlm);
        elements = json.sequence.element;

        for (var i in elements) {

          console.log(elements[i].name);
        }
    });
</script>

Result:

name
address
city
country

Upvotes: 1

Related Questions