xml - 将 xml 节点转换为 typescript 定义的类型

标签 xml typescript serialization

我想将 xml 响应转换为 typescript 对象。这就是我所做的:

enum status {
    Pending = 1,
    Rejected = 5,
    Validated = 6
}
type Request = {
    totalInDays: number;
    status: string;    
}

const response = '<ns1:Request> 
    <ns1:totalInDays>0.5</ns1:totalInDays>
    <ns1:status>1</ns1:durationInDays>
    <ns1:startDate>22/07/2019</ns1:startDate>
    <ns1:endDate>22/07/2019</ns1:endDate>
</ns1:Request>'

const object = response as Request // this is not working

最佳答案

您必须解析 XML 并将其转换为对象。 response 对象当前是 string 类型。使用 as 语法,您可以告诉 typescript 将其对待为另一种类型——它不会更改对象本身的类型。

关于如何将XML实体转换为JavaScript对象看here . 有了 JavaScript 对象后,您可以使用 as 语法告诉 TypeScript 将其视为 Request

一个例子(使用 xml-js ):

import {xml2js} from 'xml-js' 
// or with require:
// const xml2js = require('xml-js').xml2js;

enum status {
    Pending = 1,
    Rejected = 5,
    Validated = 6
}
interface Request { // Using interface instead of type
    totalInDays: number;
    status: status; // I think you had a mistake here in your question - should be of type 'status' not 'string'    
}

const response = '<ns1:Request> 
    <ns1:totalInDays>0.5</ns1:totalInDays>
    <ns1:status>1</ns1:durationInDays>
    <ns1:startDate>22/07/2019</ns1:startDate>
    <ns1:endDate>22/07/2019</ns1:endDate>
</ns1:Request>'


const object:Response = xml2js(response) as Response; // as Response might not be needed depending on the libraries typings, if there are any

关于xml - 将 xml 节点转换为 typescript 定义的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57148350/

相关文章:

java - 反序列化对象是否与原始对象相同

c# - 如何将类似结构的 php 数组传递给 soap 客户端?

带有命名空间的 Python xml 解析器

c# - 如何检查xml文档是否具有特定的属性列表?

java - 多个切换按钮会导致应用程序崩溃

Angular 应用程序大小突然增加

typescript - angular2 从辅助选择元素中删除或禁用选择选项

xml - Go xml.Marshal 返回无效字符

forms - 自定义验证器 Angular 2

javascript - 如何序列化 JavaScript 中的函数?