2016-12-15 113 views
2

將輸入XML文件轉換爲JSON輸出時,單引號屬性轉換爲雙引號。使用XSLT創建JSON輸出單引號轉換(XML到JSON)

請任何人指導我解決上述問題。

我輸入XML文件是:

<items> 
<mlu1_item> 
<title> 
<strong>Creatinine</strong> 
</title> 
<content> 
<p>Creatinine is a normal waste product</p> 
<ul> 
<li>males</li> 
<li>females</li> 
</ul> 
<p>If your creatinine level kidneys.</p> 
</content> 
<mlu1_button/> 
<button_class/> 
<link/> 
<image>icon.png</image> 
</mlu1_item> 
</items> 

XSL我所用:

<xsl:stylesheet version="2.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
xmlns:xs="http://www.w3.org/2001/XMLSchema" 
xmlns:json="http://json.org/" exclude-result-prefixes="#all"> 

<xsl:output omit-xml-declaration="yes" indent="yes" method="xml" /> 

<xsl:template match="my-node"> 
<xsl:value-of select="json:generate(.)"/> 
</xsl:template> 

<xsl:template match="items"> 
items: 
[ 
<xsl:for-each select="mlu1_item"> 
{ 
"title": "<xsl:value-of select="title/strong"/>" 
"content": "<h4><xsl:value-of select="title/strong"/></h4>**<div class='text-left'>**<xsl:apply-templates select="content"/></div>", 
"link": "", 
"image": "img/<xsl:value-of select="image"/>", 
"top": "5%", 
"left": "52%", 
"size": "", 
"color": "", 
"borderColor": "#00", 
"bgInfoColor": "#fff", 
"borderWidth": "0px", 
}, 
</xsl:for-each> 
] 
</xsl:template> 

<xsl:template match="p"> 
<xsl:copy-of select="."/> 
</xsl:template> 

<xsl:template match="ol"> 
<xsl:copy-of select="."/> 
</xsl:template> 

<xsl:template match="ul"> 
<xsl:copy-of select="."/> 
</xsl:template> 

<xsl:template match="li"> 
<xsl:copy-of select="."/> 
</xsl:template> 

<xsl:template match="content"> 
<xsl:apply-templates/> 
</xsl:template> 

</xsl:stylesheet> 

輸出JSON我爲有:

items: 
[ 
{ 
"title": "Creatinine" 
"content": "<h4>Creatinine</h4> 
**<div class="text-left">** 
<p>Creatinine is a normal waste product</p> 
<ul> 
<li>males</li> 
<li>females</li> 
</ul> 
<p>If your creatinine level kidneys.</p> 
</div>", 
"link": "", 
"image": "img/icon.png", 
"top": "5%", 
"left": "52%", 
"size": "", 
"color": "", 
"borderColor": "#00", 
"bgInfoColor": "#fff", 
"borderWidth": "0px", 
}, 
] 
}; 

但是我預期的輸出爲:

items: 
[ 
{ 
"title": "Creatinine" 
"content": "<h4>Creatinine</h4> 
**<div class='text-left'>** 
<p>Creatinine is a normal waste product</p> 
<ul> 
<li>males</li> 
<li>females</li> 
</ul> 
<p>If your creatinine level kidneys.</p> 
</div>", 
"link": "", 
"image": "img/icon.png", 
"top": "5%", 
"left": "52%", 
"size": "", 
"color": "", 
"borderColor": "#00", 
"bgInfoColor": "#fff", 
"borderWidth": "0px", 
}, 
] 
}; 

我想保持對格屬性申報單引號在JSON輸出

+0

您使用哪種XSLT處理器?最近Saxon或Altova的發佈版本支持XPath函數來序列化XML並創建JSON,因此它們可能會比一些模板做得更好,以創建格式正確,均衡或轉義的引號。 –

+0

Saxon-PE 9.6.0.7我用於轉換的版本 –

+0

您是否在oXygen中使用Saxon?至於輸出,是否應該在json.org上指定JSON? –

回答

2

你真的不想使用XML輸出方法創造的東西,是不是XML。 XML輸出方法不允許您控制是圍繞屬性值使用單引號還是雙引號,因爲它假定您正在編寫XML,而在XML中它沒有區別。

如果您想要XML中的某些其他格式不是XML的片段,這正是XPath 3.0/3.1中fn:serialize()函數的用途。

您可以使用它來創建XML片段,然後將它們合併到JSON結構中,然後您可以使用JSON輸出方法對其進行序列化; JSON輸出方法會將字符串內容中的任何雙引號轉義爲\"