Convert XML Data to Json Format AngularJS

2020-07-06 06:31发布

问题:

I am trying to use Treeview directive from AngularJS. The stored procedure is returning xml.The tree view directive takes json format. The Controller will get the data from service.I am stuck trying to convert xml to json in service.

Following is the xml structure:

<Company Data="New Company">
  <Manager Data="Working">
    <Employee Data="ABC" />
    <Employee Data="DEF" />
    <Employee Data="GHI">
      <SubEmployee Data="Approval">
        <Stuff Data="Financial" />
        <Stuff Data="Consol" />
      </SubEmployee>
      <SubEmployee Data="Rolled-Over">
        <Stuff Data="Corporate" />
      </SubEmployee>
    </Employee>
  </Manager>
</Company>

Below is the expected JSON :

[
  {
    label: "New Company",
    id: "Company",
    children: [
      {
        label: "Working",
        id: "Manager",
        children: [
          {
            label: "ABC",
            id: "Employee",
            children: [

            ]
          },
          {
            label: "DEF",
            id: "Employee",
            children: [

            ]
          },
          {
            label: "GHI",
            id: "Employee",
            children: [
              {
                label: "Approval",
                id: "SubEmployee",
                children: [
                  {
                    label: "Financial",
                    id: "Stuff",
                    children: [

                    ]
                  },
                  {
                    label: "Consol",
                    id: "Stuff",
                    children: [

                    ]
                  }
                ]
              },
              {
                label: "RolledOver",
                id: "SubEmployee",
                children: [
                  {
                    label: "Corporate",
                    id: "Stuff",
                    children: [

                    ]
                  }
                ]
              }
            ]
          }
        ]
      }
    ]

回答1:

You have two choices:

  1. Return the data from the API in the JSON format you require
  2. Convert the XML to JSON in your angular application using javascript.

I would recommend option 1 if that is possible. For option 2 take a look at this question which disucsses XML/JSON conversion in Javascript "Convert XML to JSON (and back) using Javascript"

If you read the answers on the above link you will see why option 1 is preferable. Converting between these formats can be problematic.



回答2:

If you have JQuery available in that page you can convert the XML into a DOM object by doing var data = jQuery(data);. Then, use jQuery selectors to extract the data you need out of it.

Some examples:

// Extract an attribute from a node:
$scope.event.isLive = jQuery(data).find('event').attr('state') === 'Live';

// Extract a node's value:
$scope.event.title = jQuery('title', data).text();


回答3:

A little late but I am also having to look at this option since I will be working with a CMS that only parses into XML. Which at this stage of the game I have no clue why... but I digress.

Found this on D-Zone and it seems to have potential: https://dzone.com/articles/convert-xml-to-json-in-angular-js

Basically, you make the request to get the XML, then convert it to JSON within another function. Granted you are still pulling XML data but you will be able to work with JSON which will save you a lot of time.

EX from Site (Requires 3rd party Plugin X2JS)

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

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

$http.get("Sitemap.xml",

        {

transformResponse: function (cnv) {

  var x2js = new X2JS();

  var aftCnv = x2js.xml_str2json(cnv);

  return aftCnv;

}

})

.success(function (response) {

console.log(response);

});

});

One more note, if you are using Angular like me then someone has already created a nice plugin service to use: https://github.com/johngeorgewright/angular-xml