> 웹 프론트엔드 > JS 튜토리얼 > 자바스크립트에서 xml을 json으로 변환하는 방법

자바스크립트에서 xml을 json으로 변환하는 방법

青灯夜游
풀어 주다: 2023-01-04 09:34:47
원래의
6099명이 탐색했습니다.

javascript에서 xml을 json 문자열로 변환하는 방법: 먼저 XML 문자열을 통해 XML DOM 개체를 얻거나 XML 파일을 요청한 다음 순회 및 재귀를 통해 하위 요소의 nodeValue 값을 얻습니다. . 할 수 있다.

자바스크립트에서 xml을 json으로 변환하는 방법

이 튜토리얼의 운영 환경: Windows 7 시스템, JavaScript 버전 1.8.5, Dell G3 컴퓨터.

JavaScript를 사용하여 XML을 JSON으로 변환

먼저 XML 문자열을 통해 XML DOM 개체를 생성하세요.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

/**

 * 通过传入xml的内容字符串来解析xml

 * @param xmlString xml字符串

 * @returns xml的Document对象

 */

function getXmlDocumentByXmlString(xmlString) {

    var xmlDoc = null;

    if (window.DOMParser) {

        var parser = new DOMParser();

        xmlDoc = parser.parseFromString(xmlString, "text/xml");

    } else {

        //IE

        xmlDoc = new ActiveXObject("Microsoft.XMLDOM");

        xmlDoc.async = "false";

        xmlDoc.loadXML(xmlString);

    }

    return xmlDoc;

}

로그인 후 복사

또는 XML 파일을 요청하여 XML DOM 개체를 가져옵니다.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

/**

 * 通过传入xml文件路径来解析xml文档

 * @param xmlFilePath xml文档路径,如:files/test.xml

 * @returns xml的Document对象

 */

function getXmlDocumentByFilePath(xmlFilePath) {

    //xmlDocument对象

    var xmlDoc = null;

    //xmlhttp对象

    var xmlhttp = null;

    if (window.XMLHttpRequest) {

        //IE7+, FireFox, Chrome, Opera, Safari

        xmlhttp = new XMLHttpRequest();

    } else {

        //IE6, IE5

        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");

    }

 

    xmlhttp.open("GET", xmlFilePath, false);

    xmlhttp.send();

    xmlDoc = xmlhttp.responseXML;

    return xmlDoc;

}

로그인 후 복사

다음 단계는 중요한 부분입니다. 하위 요소의 nodeValue를 순회하고 재귀적으로 획득하여 JSON 문자열을 분리하고 XML을 JSON 문자열로 변환합니다.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

/**

 * 将XML的Document对象转换为JSON字符串

 * @param xmlDoc xml的Document对象

 * @return string

 */

function convertToJSON(xmlDoc) {

    //准备JSON字符串和缓存(提升性能)

    var jsonStr = "";

    var buffer = new Array();

 

    buffer.push("{");

    //获取xml文档的所有子节点

    var nodeList = xmlDoc.childNodes;

 

    generate(nodeList);

 

    /**

     * 中间函数,用于递归解析xml文档对象,并附加到json字符串中

     * @param node_list xml文档的的nodeList

     */

    function generate(node_list) {

 

        for (var i = 0; i < node_list.length; i++) {

            var curr_node = node_list[i];

            //忽略子节点中的换行和空格

            if (curr_node.nodeType == 3) {

                continue;

            }

            //如果子节点还包括子节点,则继续进行遍历

            if (curr_node.childNodes.length > 1) {

                buffer.push("\"" + curr_node.nodeName + "\": {");

                generate(curr_node.childNodes);

            } else {

                var firstChild = curr_node.childNodes[0];

 

                if (firstChild != null) {

                    //nodeValue不为null

                    buffer.push("\"" + curr_node.nodeName + "\":\"" + firstChild.nodeValue + "\"");

                } else {

                    //nodeValue为null

                    buffer.push("\"" + curr_node.nodeName + "\":\"\"");

                }

 

            }

            if (i < (node_list.length - 2)) {

                buffer.push(",");

            } else {

                break;

            }

        }

        //添加末尾的"}"

        buffer.push("}");

    }

 

    jsonStr = buffer.join("");

    return jsonStr;

}

로그인 후 복사

Usage: xml의 Ducument 개체를 전달하여 변환된 JSON 문자열을 가져옵니다. getXmLDocumentByFilePath(xmlFilePath)或者getXmlDocumentByXmlString(xmlString)获取XML的Document对象,然后通过调用convertToJSON(xmlDocument)

적용 범위: 속성을 포함하지 않는 모든 XML 문서.

더 많은 프로그래밍 관련 지식을 보려면

프로그래밍 비디오를 방문하세요! !

위 내용은 자바스크립트에서 xml을 json으로 변환하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿