【问题标题】:Read a local XML file in Angular/Typescript and extract some node values在 Angular/Typescript 中读取本地 XML 文件并提取一些节点值
【发布时间】:2019-10-22 03:10:26
【问题描述】:

我正在尝试使用 Angular 和 typescript 加载 XML 文件,然后能够提取一些特定的节点值以将它们用于计算并在应用程序的其他某些组件中显示这些值。我对 Angular 和打字稿(以及一般的编码)完全陌生。我已经完成了 Angular 教程,但现在我正在努力开始并实现上述目标。 我想我需要: - 提供文件路径并加载文件,并将其存储在变量中 - 从 XML 转换为其他东西(JSON?) - 根据名称和属性查找某个“节点”并将值存储在变量中 - 使用 {{}} 在 HTML 中使用此变量。

我尝试了几个选项,但到目前为止都没有奏效,可能是因为我混合了不同的路线。

我现在只有:

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  template: (.... some html.... that displays title and the image below and the date using {{}} )

export class AppComponent {

title="Welcome !";
Welcome_Image="/Images/Images.JPG";
today=Date.now();

}

您能帮我完成上述任务吗?非常感谢你的帮助。

最好的问候,劳伦斯

【问题讨论】:

    标签: xml angular typescript


    【解决方案1】:

    如果您希望将其 XML 转换为 JSON,有一些包可以帮助您实现此目的。我使用了 xml2js 包。代码看起来像这样链接:

    import { promises as fsPromises } from 'fs'; 
    import { parseString } from 'xml2js';
    
    // Declare Variables
    let JSONdata = null;
    let XMLdata = null;
    
    // Read the XML file 
    
    fsPromises.readFile('../xmlParser/test.xml','utf-8')
    .then(function(value){
        XMLdata = value; 
        console.log('XML data is: '+ value);
    
        // Parse XML
        parseString(XMLdata, function(err, result){
        if(err) {   
            console.log('There was an error when parsing: ' + err);
        }
        else {
            console.log('The JSON version is: ' + JSON.stringify(result));
            console.log('The JSON version is: ' + JSON.stringify(result.root.graph)); // Use this format to extract the tags/data you are interested in
            JSONdata = result;
    
            // Write the JSON data to a file
            fsPromises.writeFile("../xmlParser/edited-test.json", JSON.stringify(JSONdata), 'utf-8')
            .then( function() { console.log('Successfully written the file') })
            .catch( function(reason) { console.log('Something went wrong when writing the file: '+ reason) });
        }
        })
    })
    
    .catch(function(reason){
        console.log('There was some problem reading the file: '+ reason)});
    
    

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-23
      • 2016-05-06
      • 2016-11-21
      相关资源
      最近更新 更多