在Angular中,可以使用xml-js
库来将2D JSON对象转换为XML。以下是一个示例解决方法:
xml-js
库。在终端中运行以下命令:npm install xml-js --save
xml-js
库:import { xml2js, js2xml } from 'xml-js';
convertJsonToXml(jsonData: any): string {
const xmlData = js2xml(jsonData, { compact: true, ignoreComment: true, spaces: 4 });
return xmlData;
}
const json = {
name: 'John',
age: 30,
address: {
street: '123 Street',
city: 'City',
country: 'Country'
}
};
const xml = this.convertJsonToXml(json);
console.log(xml);
在上面的示例中,我们首先定义了一个JSON对象json
,然后通过调用convertJsonToXml
方法将其转换为XML。最后,我们将转换后的XML打印到控制台上。
请注意,在js2xml
方法中,我们使用了一些选项来生成紧凑的XML({ compact: true }
),忽略注释({ ignoreComment: true }
)并使用4个空格进行缩进({ spaces: 4 }
)。您可以根据需要调整这些选项。
这是一个简单的示例,希望对您有所帮助!