XML转换

2024-02-16 13:48 更新

将XML文本转换为JavaScript对象可以更轻松地处理和操作数据,并且更适合在JavaScript应用程序中使用。

语言基础类库提供ConvertXML类将XML文本转换为JavaScript对象,输入为待转换的XML字符串及转换选项,输出为转换后的JavaScript对象。具体转换选项可见@ohos.convertxml

注意事项

XML解析及转换需要确保传入的XML数据符合标准格式。

开发步骤

此处以XML转为JavaScript对象后获取其标签值为例,说明转换效果。

  1. 引入模块。

    1. import convertxml from '@ohos.convertxml';
  2. 输入待转换的XML,设置转换选项。

    1. let xml =
    2. '<?xml version="1.0" encoding="utf-8"?>' +
    3. '<note importance="high" logged="true">' +
    4. ' <title>Happy</title>' +
    5. ' <todo>Work</todo>' +
    6. ' <todo>Play</todo>' +
    7. '</note>';
    8. let options = {
    9. // trim: false 转换后是否删除文本前后的空格,否
    10. // declarationKey: "_declaration" 转换后文件声明使用_declaration来标识
    11. // instructionKey: "_instruction" 转换后指令使用_instruction标识
    12. // attributesKey: "_attributes" 转换后属性使用_attributes标识
    13. // textKey: "_text" 转换后标签值使用_text标识
    14. // cdataKey: "_cdata" 转换后未解析数据使用_cdata标识
    15. // docTypeKey: "_doctype" 转换后文档类型使用_doctype标识
    16. // commentKey: "_comment" 转换后注释使用_comment标识
    17. // parentKey: "_parent" 转换后父类使用_parent标识
    18. // typeKey: "_type" 转换后元素类型使用_type标识
    19. // nameKey: "_name" 转换后标签名称使用_name标识
    20. // elementsKey: "_elements" 转换后元素使用_elements标识
    21. trim: false,
    22. declarationKey: "_declaration",
    23. instructionKey: "_instruction",
    24. attributesKey: "_attributes",
    25. textKey: "_text",
    26. cdataKey: "_cdata",
    27. docTypeKey: "_doctype",
    28. commentKey: "_comment",
    29. parentKey: "_parent",
    30. typeKey: "_type",
    31. nameKey: "_name",
    32. elementsKey: "_elements"
    33. }
  3. 调用转换函数,打印结果。

    1. let conv = new convertxml.ConvertXML();
    2. let result = conv.convertToJSObject(xml, options);
    3. let strRes = JSON.stringify(result); // 将js对象转换为json字符串,用于显式输出
    4. console.info(strRes);
    5. // 也可以直接处理转换后的JS对象,获取标签值
    6. let title = result['_elements'][0]['_elements'][0]['_elements'][0]['_text']; // 解析<title>标签对应的值
    7. let todo = result['_elements'][0]['_elements'][1]['_elements'][0]['_text']; // 解析<todo>标签对应的值
    8. let todo2 = result['_elements'][0]['_elements'][2]['_elements'][0]['_text']; // 解析<todo>标签对应的值
    9. console.info(title); // Happy
    10. console.info(todo); // Work
    11. console.info(todo2); // Play

    输出结果如下所示:

    1. strRes:
    2. {"_declaration":{"_attributes":{"version":"1.0","encoding":"utf-8"}},"_elements":[{"_type":"element","_name":"note",
    3. "_attributes":{"importance":"high","logged":"true"},"_elements":[{"_type":"element","_name":"title",
    4. "_elements":[{"_type":"text","_text":"Happy"}]},{"_type":"element","_name":"todo",
    5. "_elements":[{"_type":"text","_text":"Work"}]},{"_type":"element","_name":"todo",
    6. "_elements":[{"_type":"text","_text":"Play"}]}]}]}
    7. title:Happy
    8. todo:Work
    9. todo2:Play
以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号