Angular2 typescript - print pretty XML

▼魔方 西西 提交于 2020-02-13 08:10:47

问题


I have this following XML string I got from the server:

<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>

But I want to beautify it in my module:

<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>

What is the best way to print it beautified?


回答1:


You can create a custom pipe for this that uses vkbeautify under the hoods.

npm install -S vkbeautify

Custom xml pipe example:

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);
    }
}

Declare the custom pipe in your app.module, e.g.:

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

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

And then you can use the custom pipe in your templates like so:

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


来源:https://stackoverflow.com/questions/42268268/angular2-typescript-print-pretty-xml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!