我正在使用Javascript将XML文档转换为特殊的JSON格式。
使用Javascript中的标准DOM处理方法,我需要帮助构建一个高效,优雅的算法来确定节点是否包含任何非文本节点或属性,并根据节点内容以不同方式组织JSON对象。
示例:
<demo>
<title>Text Test</title>
<textonly id="demoText">
This is a text-only node! It doesn't need a 'text' property.
</textonly>
<mixed id="aMixedNode">
This is text
<!-- This is a comment node -->
<another />
<!-- Note that this element has not 4, but 7 nodes -- counting the text between the non-text nodes! -->
More text!
</mixed>
<textonly id="specialText" special="something">
This would be a text-only node, but it's not because the attribute requires us to create a 'text' property
</textonly>
<textonly id="validText">This is a text node!</textonly>
<nontext />
<final>End of demo!</final>
</demo>
应转换为:
{
title: 'Text Test',
demoText: 'This is a text-only node! It doesn't need a 'text' property.',
aMixedNode: {
text: [
'This is text',
'More text!'
],
another: null
},
specialText: {
special: 'something',
text: 'This would be a text-only node, but it's not because the attribute requires us to create a 'text' property'
},
validText: 'This is a text node!',
nonText: null,
final: 'End of demo!'
}
注意:
修剪所有文字值;删除/忽略空文本值
多个文本节点,即当文本和其他节点混合时,文本存储在数组中。如果只有一个文本值,我们只将其存储为字符串。
ID属性用作属性名称(如果存在);否则使用节点名称。同一个节点名称的多个实例(都没有ID)将存储在一个数组中(但目前尚未对此进行说明)。
与空文本节点一样,删除/忽略注释节点