首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Node中使用saxon处理XPath表达式

如何在Node中使用saxon处理XPath表达式
EN

Stack Overflow用户
提问于 2021-06-15 02:04:03
回答 1查看 406关注 0票数 0

我用打字本写了下面的课:

代码语言:javascript
复制
import * as saxon from 'saxon-js';

export class XsltXpath {

    private static readonly SINGLETON: XsltXpath = new XsltXpath();

    static transform(styleSheetFile: string, sourceFile: string): any {
        return XsltXpath.SINGLETON.transformViaXsl(styleSheetFile, sourceFile);
    }

    static pick(sourceFile: string, xpathQuery: string): any {
        return XsltXpath.SINGLETON.pickViaXpath(sourceFile, xpathQuery);
    }

    private async transformViaXsl(styleSheetFile: string, sourceFile: string): Promise<any> {

        const output: { principalResult: any; } = await saxon.transform({
            stylesheetFileName: styleSheetFile,
            sourceFileName: sourceFile,
            destination: 'serialized'
        }, 'async');

        return output.principalResult;
    }

    private pickViaXpath(sourceFile: string, xpathQuery: string): any {
        const doc = saxon.getResource({
            file: sourceFile,
            type: "xml"
        });
        const result = saxon.XPath.evaluate(xpathQuery, doc);
        const output = saxon.serialize(result, { method: 'xml', indent: true, 'omit-xml-declaration': true });
        console.log(output);
        return output;
    }
}

...and,我是这样用它的:

代码语言:javascript
复制
const output: any = await XsltXpath.transform('./testdata/stylesheet.sef.json', './testdata/data.xml');
    console.log('OUTPUT: ', output);
    res.send(output);

OR

    const output: any = await XsltXpath.pick('./testdata/data.xml', 'catalog/cd//artist');
    console.log('OUTPUT: ', output);
    res.send(output);

"transform"-Method工作得很好,但是当我使用"pick"-Method时,我总是会得到以下错误:

代码语言:javascript
复制
message: 'Context item for child axis is not a node - supplied:HashTrie map{}',
  name: 'XError',
  code: 'XPTY0020'

我的XPath表达式在这种测试数据上是有效的,因此我假设我必须以另一种方式提供表达式:

代码语言:javascript
复制
<catalog>
  <cd>
    <title>Empire Burlesque</title>
    <artist>Bob Dylan</artist>
    <country>USA</country>
    <company>Columbia</company>
    <price>10.90</price>
    <year>1985</year>
  </cd>
...
</catalog>

我做错什么了,泰克斯。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-06-15 07:47:30

SaxonJS.getResource()是异步的,并返回一个承诺;我认为您已经向SaxonJS.XPath.Evaluate()提供了这个承诺,它将其视为一个通用Javascript对象。

你需要这样的东西

代码语言:javascript
复制
saxon.getResource({
            file: sourceFile,
            type: "xml"
        })
.then((doc) => saxon.XPath.evaluate(xpathQuery, doc))

当然,如果您不希望整个过程是异步的,那么您就不必使用saxon.getResource() - doc只是一个DOM文档节点,您可以任意创建它。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67979111

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档