• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

TypeScript xml-js.xml2js函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了TypeScript中xml-js.xml2js函数的典型用法代码示例。如果您正苦于以下问题:TypeScript xml2js函数的具体用法?TypeScript xml2js怎么用?TypeScript xml2js使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了xml2js函数的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的TypeScript代码示例。

示例1: getTranslationAsync

    /**
     * Translates a text string from one language to another.
     * @method getTranslationAsync
     * @param {string} text 
     * Required. A string representing the text to translate. The size of the text must not exceed 10000 characters.
     * @param {string} from 
     * Optional. A string representing the language code of the translation text. For example, en for English.
     * @param {string} to 
     * Optional. A string representing the language code to translate the text into.
     * @returns {string}
     * A string representing the translated text. 
     */
    public async getTranslationAsync(text: string, from?: string, to: string = "en"): Promise<string | undefined> {

        let translatorApiKey = process.env.COGNITIVE_TRANSLATOR_API_KEY;

        if (!translatorApiKey) {
            throw new Error('translator text api key is undefined')
        }

        if (!text) {
            throw new Error('text argument is empty or undefined')
        }

        let encodedText = encodeURIComponent(text);
        let url = `${baseUrl}/Translate?text=${encodedText}`;

        if (from) {
            url += `&from=${from}`;
        }

        if (to) {
            url += `&to=${to}`
        }

        let response = await fetch(url,
            {
                method: 'GET',
                headers:
                    {
                        'Ocp-Apim-Subscription-Key': translatorApiKey,
                    }
            })
            .catch(error => console.error(error));

        if (response && response.status && response.status >= 200 && response.status <= 299) {
            let xmlcontent = await response.text()

            if (xmlcontent) {
                let json = xmljs.xml2js(xmlcontent, { compact: true, ignoreAttributes: true });

                if (json && json.string && json.string._text) {
                    return json.string._text;
                }
            }
        }

        return undefined;
    }
开发者ID:LucasChies,项目名称:Medication-Helper-idtpoa,代码行数:59,代码来源:cognitive-translator.ts


示例2: extractDocumentRefs

    private extractDocumentRefs(xmlData: string): IDocumentRefs {
        const xmlObj = xml2js(xmlData, { compact: true }) as XMLElementCompact;
        const sectionProp = xmlObj["w:document"]["w:body"]["w:sectPr"];

        const headerProps: XMLElementCompact = sectionProp["w:headerReference"];
        let headersXmlArray: XMLElementCompact[];
        if (headerProps === undefined) {
            headersXmlArray = [];
        } else if (Array.isArray(headerProps)) {
            headersXmlArray = headerProps;
        } else {
            headersXmlArray = [headerProps];
        }
        const headers = headersXmlArray.map((item) => {
            if (item._attributes === undefined) {
                throw Error("header referecne element has no attributes");
            }
            return {
                type: item._attributes["w:type"] as HeaderReferenceType,
                id: this.parseRefId(item._attributes["r:id"] as string),
            };
        });

        const footerProps: XMLElementCompact = sectionProp["w:footerReference"];
        let footersXmlArray: XMLElementCompact[];
        if (footerProps === undefined) {
            footersXmlArray = [];
        } else if (Array.isArray(footerProps)) {
            footersXmlArray = footerProps;
        } else {
            footersXmlArray = [footerProps];
        }

        const footers = footersXmlArray.map((item) => {
            if (item._attributes === undefined) {
                throw Error("footer referecne element has no attributes");
            }
            return {
                type: item._attributes["w:type"] as FooterReferenceType,
                id: this.parseRefId(item._attributes["r:id"] as string),
            };
        });

        return { headers, footers };
    }
开发者ID:dolanmiu,项目名称:docx,代码行数:45,代码来源:import-dotx.ts


示例3: getLanguageNameAsync

    /**
     * Retrieves friendly names for the languages passed in as the parameter languageCode, 
     * and localized using the passed locale language.
     * @method getLanguageNameAsync
     * @param {string} languageCode 
     * Required. A string representing the ISO 639-1 language code to retrieve the friendly names for.
     * @param {string} locale
     * Optional. A string representing a combination of an ISO 639 two-letter lowercase culture code 
     * associated with a language and an ISO 3166 two-letter uppercase subculture code to localize the language names or a ISO 639 lowercase culture code by itself.
     * @returns {string}
     * A string representing the translated text. 
     */
    public async getLanguageNameAsync(languageCode: string, locale: string = "en"): Promise<string | undefined> {

        let code = encodeURIComponent(languageCode);

        let translatorApiKey = process.env.COGNITIVE_TRANSLATOR_API_KEY;

        // Check if environment variables are correct
        if (translatorApiKey == undefined) {
            console.log("Cognitive Services - Translation - Url or Api Key undefined.");
            return undefined;
        }

        let query = `${baseUrl}/GetLanguageNames?locale=${locale}`;

        let response = await fetch(query,
            {
                method: 'POST',
                headers:
                    {
                        'Ocp-Apim-Subscription-Key': translatorApiKey,
                        'Content-Type': 'text/xml'
                    },
                body:
                    `<ArrayOfstring xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
                        <string>${languageCode}</string>
                    </ArrayOfstring>`
            })
            .catch(error => console.error(error));

        if (response && response.status && response.status >= 200 && response.status <= 299) {
            let xmlcontent = await response.text()

            if (xmlcontent) {
                let json = xmljs.xml2js(xmlcontent, { compact: true, ignoreAttributes: true });

                if (json && json.ArrayOfstring && json.ArrayOfstring.string && json.ArrayOfstring.string._text) {
                    return json.ArrayOfstring.string._text;
                }
            }
        }

        return undefined;
    }
开发者ID:LucasChies,项目名称:Medication-Helper-idtpoa,代码行数:55,代码来源:cognitive-translator.ts


示例4: findReferenceFiles

 private findReferenceFiles(xmlData: string): IRelationshipFileInfo[] {
     const xmlObj = xml2js(xmlData, { compact: true }) as XMLElementCompact;
     const relationXmlArray = Array.isArray(xmlObj.Relationships.Relationship)
         ? xmlObj.Relationships.Relationship
         : [xmlObj.Relationships.Relationship];
     const relationships: IRelationshipFileInfo[] = relationXmlArray
         .map((item: XMLElementCompact) => {
             if (item._attributes === undefined) {
                 throw Error("relationship element has no attributes");
             }
             return {
                 id: this.parseRefId(item._attributes.Id as string),
                 type: schemeToType[item._attributes.Type as string],
                 target: item._attributes.Target as string,
             };
         })
         .filter((item) => item.type !== null);
     return relationships;
 }
开发者ID:dolanmiu,项目名称:docx,代码行数:19,代码来源:import-dotx.ts


示例5: newInstance

    /**
     * Creates new Style based on the given styles.
     * Parses the styles and convert them to XmlComponent.
     * Example content from styles.xml:
     * <?xml version="1.0">
     * <w:styles xmlns:mc="some schema" ...>
     *
     *   <w:style w:type="paragraph" w:styleId="Heading1">
     *           <w:name w:val="heading 1"/>
     *           .....
     *   </w:style>
     *
     *   <w:style w:type="paragraph" w:styleId="Heading2">
     *           <w:name w:val="heading 2"/>
     *           .....
     *   </w:style>
     *
     *   <w:docDefaults>Or any other element will be parsed to</w:docDefaults>
     *
     * </w:styles>
     * @param externalStyles context from styles.xml
     */
    public newInstance(xmlData: string): Styles {
        const xmlObj = xml2js(xmlData, { compact: false }) as XMLElement;

        let stylesXmlElement: XMLElement | undefined;
        for (const xmlElm of xmlObj.elements || []) {
            if (xmlElm.name === "w:styles") {
                stylesXmlElement = xmlElm;
            }
        }
        if (stylesXmlElement === undefined) {
            throw new Error("can not find styles element");
        }

        const importedStyle = new Styles(new ImportedRootElementAttributes(stylesXmlElement.attributes));
        const stylesElements = stylesXmlElement.elements || [];
        for (const childElm of stylesElements) {
            importedStyle.push(convertToXmlComponent(childElm) as ImportedXmlComponent);
        }
        return importedStyle;
    }
开发者ID:dolanmiu,项目名称:docx,代码行数:42,代码来源:external-styles-factory.ts


示例6: Error

            .map(async (reference, i) => {
                const relationshipFileInfo = documentRelationships.find((rel) => rel.id === reference.id);

                if (relationshipFileInfo === null || !relationshipFileInfo) {
                    throw new Error(`Can not find target file for id ${reference.id}`);
                }

                const xmlData = await zipContent.files[`word/${relationshipFileInfo.target}`].async("text");
                const xmlObj = xml2js(xmlData, { compact: false, captureSpacesBetweenElements: true }) as XMLElement;

                if (!xmlObj.elements) {
                    return undefined;
                }

                const xmlElement = xmlObj.elements.reduce((acc, current) => (current.name === "w:ftr" ? current : acc));

                const importedComp = convertToXmlComponent(xmlElement) as ImportedXmlComponent;
                const wrapper = new FooterWrapper(media, startingRelationshipId + i, importedComp);
                await this.addRelationshipToWrapper(relationshipFileInfo, zipContent, wrapper, media);

                return { type: reference.type, footer: wrapper };
            })
开发者ID:dolanmiu,项目名称:docx,代码行数:22,代码来源:import-dotx.ts


示例7: checkIfTitlePageIsDefined

    private checkIfTitlePageIsDefined(xmlData: string): boolean {
        const xmlObj = xml2js(xmlData, { compact: true }) as XMLElementCompact;
        const sectionProp = xmlObj["w:document"]["w:body"]["w:sectPr"];

        return sectionProp["w:titlePg"] !== undefined;
    }
开发者ID:dolanmiu,项目名称:docx,代码行数:6,代码来源:import-dotx.ts


示例8: fromXmlString

 /**
  * Converts the xml string to a XmlComponent tree.
  *
  * @param importedContent xml content of the imported component
  */
 public static fromXmlString(importedContent: string): ImportedXmlComponent {
     const xmlObj = xml2js(importedContent, { compact: false }) as XmlElement;
     return convertToXmlComponent(xmlObj) as ImportedXmlComponent;
 }
开发者ID:dolanmiu,项目名称:docx,代码行数:9,代码来源:imported-xml-component.ts


示例9: it

 it("should convert to xml component", () => {
     const xmlObj = xml2js(xmlString, { compact: false }) as Element;
     const converted = convertToXmlComponent(xmlObj);
     expect(converted).to.deep.equal(convertedXmlElement);
 });
开发者ID:dolanmiu,项目名称:docx,代码行数:5,代码来源:imported-xml-component.spec.ts


示例10: memoize

export const xmlToTreeNode = memoize((xml: string): TreeNode => {
  return normalizeTree(xml2js(xml).elements[0]);
});
开发者ID:cryptobuks,项目名称:tandem,代码行数:3,代码来源:xml.ts



注:本文中的xml-js.xml2js函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
TypeScript xml-writer.toString函数代码示例发布时间:2022-05-25
下一篇:
TypeScript xml.element函数代码示例发布时间:2022-05-25
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap