我需要使用 saxonjs 將 json 轉換為 xml,我不知道如何將鍵與 xml 節點匹配,我正在尋找一些示例,因為它們都不適合我,這是我的代碼
const issue = {
id: 1,
details: {
type: 'urgent',
description: 'Description of issue comes here',
date: '2021-12-12',
}
};
saxonJS.transform({
stylesheetLocation: './issue.sef.json',
sourceType: 'json',
sourceText: issue,
destination: 'serialized',
}, 'async').then(data => {
fs.open('output.xml', 'w', function(err, fd) {
fs.write(fd, data.principalResult, (err2, bytes) => {
if(err2) {
console.log(err2);
}
});
});
res.status(200).send('Ok');
})
.catch(err => {
console.log(err);
res.status(500).send('error');
});
這是我試圖實作的輸出
<xml>
<issue id="1">
<description>
<![CDATA[
Description of issue comes here
]]>
</description>
<type>urgent</type>
<date>2021-12-12</date>
</issue>
</xml>
你能幫我用 xslt 模板嗎?
uj5u.com熱心網友回復:
您顯示的輸入是一個 JavaScript 物件,它不是 JSON 規范嚴格語法規則中的 JSON。
所以我認為最好使用JSON.stringify來創建 JSON 并將其傳遞給 XPath 3.1 函式parse-json來創建 JSON 或使用 Saxon-JS 2.3 功能來獲取 JSON 文本,只需確保您正確JSON.stringify編輯了該物件。
至于示例 XSLT,這看起來很簡單,為了 XSLT 的可讀性,下面的示例僅使用帶有 XSLT 源代碼的 JavaScript 字串并通過 Saxon API 運行它:
const SaxonJS = require("saxon-js");
const issue = {
id: 1,
details: {
type: 'urgent',
description: 'Description of issue comes here',
date: '2021-12-12',
}
};
const xslt = `<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="3.0" expand-text="yes">
<xsl:output indent="yes" cdata-section-elements="description"/>
<xsl:template match=".">
<xml>
<issue id="{?id}">
<description>{?details?description}</description>
<type>{?details?type}</type>
<date>{?details?date}</date>
</issue>
</xml>
</xsl:template>
</xsl:stylesheet>`;
const result = SaxonJS.XPath.evaluate(`transform(map {
'stylesheet-text' : $xslt,
'initial-match-selection' : parse-json($json),
'delivery-format' : 'serialized'
})?output`,
[],
{ params :
{
json : JSON.stringify(issue),
xslt : xslt
}
});
當然,最后您可以先將 XSLT 編譯為 SEF/JSON,然后按您嘗試的方式運行它。
為您提供一個使用兩個不同模板和應用模板的示例 XSLT,以下內容不是使用行內代碼處理嵌套物件/映射,而是將其處理推到不同的模板:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="3.0" expand-text="yes" xmlns:map="http://www.w3.org/2005/xpath-functions/map" exclude-result-prefixes="#all">
<xsl:output indent="yes" cdata-section-elements="description"/>
<xsl:template match=".[. instance of map(*) and map:contains(., 'id')]">
<xml>
<issue id="{?id}">
<xsl:apply-templates select="?details"/>
</issue>
</xml>
</xsl:template>
<xsl:template match=".[. instance of map(*) and map:contains(., 'description')]">
<description>{?description}</description>
<type>{?type}</type>
<date>{?date}</date>
</xsl:template>
</xsl:stylesheet>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/389428.html
