Angular2 Typescript - 打印漂亮的XML

12

我从服务器得到了以下的XML字符串:

<find-item-command xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" find-method="Criteria" item-class="com" only-id="false" xsi:schemaLocation=""> <criteria> <criterion> <descriptors> <descriptor>DPSystemEventItem</descriptor> </descriptors> <value>cluster.manager.active</value> </criterion> </criteria> </find-item-command>

但我想在我的模块中美化它:

<find-item-command
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" find-method="Criteria" item-class="com" only-id="false" xsi:schemaLocation="">
    <criteria>
        <criterion>
            <descriptors>
                <descriptor>DPSystemEventItem</descriptor>
            </descriptors>
            <value>cluster.manager.active</value>
        </criterion>
    </criteria>
</find-item-command>

最佳打印方式是什么?

2个回答

21

您可以创建一个自定义管道,使用vkbeautify在内部实现。

npm install -S vkbeautify

自定义 xml 管道示例:

import * as vkbeautify from 'vkbeautify';
import { Pipe, PipeTransform } from "@angular/core";

@Pipe({
    name: 'xml'
})
export class XmlPipe implements PipeTransform {
    transform(value: string): string {
        return vkbeautify.xml(value);
    }
}

在你的 app.module 中声明自定义管道,例如:

import { AppComponent } from './app.component';
import { XmlPipe } from '...';

@NgModule({
    declarations: [
        AppComponent,
        ...,
        ...,
        XmlPipe
    ],
    ...

然后,您可以在模板中像这样使用自定义管道:

<pre>{{xmlString | xml}}</pre>

1
这对我也起作用了。我使用了 Prism.js 来获得语法高亮。 - sofly
2
找不到模块 'vkbeautify',有人可以帮忙吗? - Debadatta
注意事项:在 HTML 中正确显示,必须 强制 使用 pre 标签。我曾经因为不知道这一点而卡了很长时间! - tejas n

1

我按照@Saeb Amini的方法操作,但是出现了“找不到模块的声明文件”的错误。我运行了以下命令:

npm install -D @types/vkbeautify

然后它就可以正常工作了。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接