微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

xml 到 json 的转换 - 如何将子节点和子元素从 xml 转换为 json

如何解决xml 到 json 的转换 - 如何将子节点和子元素从 xml 转换为 json

我们正在尝试将 xml 转换为 json。 子元素“EmployeeCode”无法识别。错误:在第 15 行执行 XSLT 时出错:xml-to-json:必须具有 key 属性的子元素。需要考虑xml到json转换的子元素和子元素。

xml文件

<root>
    <Name>Alex</Name>
    <Age>42</Age>
    <item>
        <number>314</number>
        <name>foo</name>
        <EmployeeCode>
            <id>F21</id>
            <Department>
                <Designation>Engineer</Designation>
            </Department>
            <Status>Contractor</Status>
        </EmployeeCode>
    </item>
    <item>
        <number>42</number>
        <name>bar</name>
        <EmployeeCode>
            <id>F24</id>
            <Department>
                <Designation>Manager</Designation>
            </Department>
            <Status>Full-time</Status>
        </EmployeeCode>
    </item>
    <data>test</data>
</root>

xsl 代码

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="#all"
    xmlns="http://www.w3.org/2005/xpath-functions"
    expand-text="yes"
    version="3.0">

  <xsl:output method="text"/>

  <xsl:template match="/">
      <xsl:variable name="json-xml">
          <xsl:apply-templates/>
      </xsl:variable>
      <xsl:value-of select="xml-to-json($json-xml,map { 'indent' : true() })"/>
  </xsl:template>
  
  <xsl:template match="*[not(*)]">
    <string key="{local-name()}">{.}</string>
  </xsl:template>
  
  <xsl:template match="*[not(*) and . castable as xs:double]">
    <number key="{local-name()}">{.}</number>
  </xsl:template>
  
  <xsl:template match="*[*]">
      <map>
          <xsl:for-each-group select="*" group-by="node-name()">
              <xsl:choose>
                  <xsl:when test="current-group()[2]">
                      <array key="{local-name()}">
                          <xsl:apply-templates select="current-group()"/>
                      </array>
                  </xsl:when>
                  <xsl:otherwise>
                      <xsl:apply-templates select="current-group()"/>
                  </xsl:otherwise>
              </xsl:choose>
          </xsl:for-each-group>
      </map>
  </xsl:template>
  
      <xsl:template match="node()|@*">        
        <!-- Including any attributes it has and any child nodes -->
        <xsl:apply-templates select="@*|node()"/>
    </xsl:template>

</xsl:stylesheet>

预期的 Json 文件

{
    "Name": "Alex","Age": 42,"item": [
      {
        "number": 314,"name": "foo","EmployeeCode": {
          "id": "F21","Department": {
            "Designation": "Engineer"
          },"Status": "Contractor"
        }
      },{
        "number": 42,"name": "bar","EmployeeCode": {
          "id": "F24","Department": {
            "Designation": "Manager"
          },"Status": "Full-time"
        }
      }
    ],"data": "test"
  }

解决方法

这是对之前代码的改进尝试:

-----> Building on the Heroku-20 stack
-----> Using buildpack: heroku/python
-----> Python app detected
-----> No Python version was specified. Using the buildpack default: python-3.9.5
       To use a different version,see: https://devcenter.heroku.com/articles/python-runtimes
-----> Installing python-3.9.5
-----> Installing pip 20.2.4,setuptools 47.1.1 and wheel 0.36.2
-----> Installing SQLite3
-----> Installing requirements with pip
       Collecting asgiref==3.3.1
         Downloading asgiref-3.3.1-py3-none-any.whl (19 kB)
       Collecting Django==3.1.5
         Downloading Django-3.1.5-py3-none-any.whl (7.8 MB)
       Collecting django-crispy-forms==1.10.0
         Downloading django_crispy_forms-1.10.0-py3-none-any.whl (107 kB)
       Collecting pytz==2020.5
         Downloading pytz-2020.5-py2.py3-none-any.whl (510 kB)
       Collecting sqlparse==0.4.1
         Downloading sqlparse-0.4.1-py3-none-any.whl (42 kB)
       Installing collected packages: asgiref,sqlparse,pytz,Django,django-crispy-forms
       Successfully installed Django-3.1.5 asgiref-3.3.1 django-crispy-forms-1.10.0 pytz-2020.5 sqlparse-0.4.1
-----> $ python Project/manage.py collectstatic --noinput
       Traceback (most recent call last):
         File "/tmp/build_784131b5/Project/manage.py",line 22,in <module>
           main()
         File "/tmp/build_784131b5/Project/manage.py",line 18,in main
           execute_from_command_line(sys.argv)
         File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py",line 401,in execute_from_command_line
           utility.execute()
         File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py",line 345,in execute
           settings.INSTALLED_APPS
         File "/app/.heroku/python/lib/python3.9/site-packages/django/conf/__init__.py",line 82,in __getattr__
           self._setup(name)
         File "/app/.heroku/python/lib/python3.9/site-packages/django/conf/__init__.py",line 69,in _setup
           self._wrapped = Settings(settings_module)
         File "/app/.heroku/python/lib/python3.9/site-packages/django/conf/__init__.py",line 170,in __init__
           mod = importlib.import_module(self.SETTINGS_MODULE)
         File "/app/.heroku/python/lib/python3.9/importlib/__init__.py",line 127,in import_module
           return _bootstrap._gcd_import(name[level:],package,level)
         File "<frozen importlib._bootstrap>",line 1030,in _gcd_import
         File "<frozen importlib._bootstrap>",line 1007,in _find_and_load
         File "<frozen importlib._bootstrap>",line 986,in _find_and_load_unlocked
         File "<frozen importlib._bootstrap>",line 680,in _load_unlocked
         File "<frozen importlib._bootstrap_external>",line 855,in exec_module
         File "<frozen importlib._bootstrap>",line 228,in _call_with_frames_removed
         File "/tmp/build_784131b5/Project/Project/settings.py",line 63,in <module>
           'DIRS': [BASE_DIR / 'templates'],TypeError: unsupported operand type(s) for /: 'str' and 'str'  !     Error while running '$ python Project/manage.py collectstatic
--noinput'.
       See traceback above for details.
       You may need to update application code to resolve this error.
       Or,you can disable collectstatic for this application:
          $ heroku config:set DISABLE_COLLECTSTATIC=1
       https://devcenter.heroku.com/articles/django-assets
****** Collectstatic environment variables:
       PYTHONUNBUFFERED=1
       PKG_CONFIG_PATH=/app/.heroku/vendor/lib/pkg-config:/app/.heroku/python/lib/pkg-config:
       DEBUG_COLLECTSTATIC=1
       BPLOG_PREFIX=buildpack.python
       PWD=/tmp/build_784131b5
       HOME=/app
       LANG=en_US.UTF-8
       SOURCE_VERSION=63bcedafe22d659d05bd224cf397b61853034b97
       REQUEST_ID=0ee34e22-e730-3756-4517-01cb87e9ab5b
       ENV_DIR=/tmp/d20210517-47-48ac3y
       PYTHONPATH=.
       CPLUS_INCLUDE_PATH=/app/.heroku/vendor/include:/app/.heroku/python/include:
       BIN_DIR=/tmp/codon/tmp/buildpacks/0f40890b54a617ec2334fac0439a123c6a0c1136/bin
       LIBRARY_PATH=/app/.heroku/vendor/lib:/app/.heroku/python/lib:
       SHLVL=1
       LD_LIBRARY_PATH=/app/.heroku/vendor/lib:/app/.heroku/python/lib:
       PIP_NO_PYTHON_VERSION_WARNING=1
       BUILDPACK_LOG_FILE=/dev/fd/3
       STACK=heroku-20
       BUILD_DIR=/tmp/build_784131b5
       CACHE_DIR=/tmp/codon/tmp/cache
       PATH=/app/.heroku/python/bin:/app/.heroku/vendor/bin::/usr/local/bin:/usr/local/bin:/usr/bin:/bin:/tmp/codon/tmp/buildpacks/0f40890b54a617ec2334fac0439a123c6a0c1136/vendor/
       EXPORT_PATH=/tmp/codon/tmp/buildpacks/0f40890b54a617ec2334fac0439a123c6a0c1136/bin/../export
       C_INCLUDE_PATH=/app/.heroku/vendor/include:/app/.heroku/python/include:
       DYNO=run.2787
       PROFILE_PATH=/tmp/build_784131b5/.profile.d/python.sh
       OLDPWD=/tmp/codon/tmp/buildpacks/0f40890b54a617ec2334fac0439a123c6a0c1136
       _=/usr/bin/env  !     Push rejected,failed to compile Python app.  !     Push failed

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。