javascript - 将 XML 数据转换为 Json 格式 AngularJS

标签 javascript xml json angularjs c#-4.0

我正在尝试使用 AngularJS 的 Treeview 指令。存储过程返回 xml。 TreeView 指令采用 json 格式。 Controller 将从服务中获取数据。我一直在尝试在服务中将 xml 转换为 json。

xml结构如下:

<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>

下面是预期的 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. 以您需要的 JSON 格式从 API 返回数据
  2. 使用 javascript 在 Angular 应用程序中将 XML 转换为 JSON。

如果可能的话,我会推荐选项 1。对于选项 2,请查看此问题,该问题讨论了 Javascript 中的 XML/JSON 转换 "Convert XML to JSON (and back) using Javascript "

如果您阅读以上链接中的答案,您就会明白为什么选项 1 更可取。在这些格式之间进行转换可能会出现问题。

关于javascript - 将 XML 数据转换为 Json 格式 AngularJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20664311/

相关文章:

javascript - ngFor 中的 ngModelGroup?

android - 滑动标签 - NullPointerException - Toolbar.getTitle()

json - Go:解码 JSON 嵌套对象数组

java - 使用文档类在java中合并xml文件

java - 在 JSP 中将 xml 选择转换为数字

sql - 从内连接简化 SQL row_to_json

javascript - 理解为什么这不需要 JSON.stringify

javascript - 使用 JavaScript 在点击时重置计时器

javascript - 隐藏所有后代表行

javascript - 如何在 JavaScript 中重定向自定义生成的 URL?