Angular2打字稿 - 打印漂亮的XML

时间:2017-02-16 08:11:49

标签: javascript xml angular typescript pretty-print

我从服务器获得以下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>

打印美化的最佳方式是什么?

1 个答案:

答案 0 :(得分:11)

您可以为此创建一个使用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>