Javascript + XML: Parsing text-only and mixed nodes (into JSON) -
i'm working on converting xml document special json format using javascript.
using standard dom processing methods in javascript, need constructing efficient, elegant algorithm determining whether node contains non-text nodes or attributes, , organizing json object differently depending on node contents.
example:
<demo> <title>text test</title> <textonly id="demotext"> text-only node! doesn't need 'text' property. </textonly> <mixed id="amixednode"> text <!-- comment node --> <another /> <!-- note element has not 4, 7 nodes -- counting text between non-text nodes! --> more text! </mixed> <textonly id="specialtext" special="something"> text-only node, it's not because attribute requires create 'text' property </textonly> <textonly id="validtext">this text node!</textonly> <nontext /> <final>end of demo!</final> </demo>
should convert to:
{ title: 'text test', demotext: 'this text-only node! doesn't need 'text' property.', amixednode: { text: [ 'this text', 'more text!' ], another: null }, specialtext: { special: 'something', text: 'this text-only node, it's not because attribute requires create 'text' property' }, validtext: 'this text node!', nontext: null, final: 'end of demo!' }
notes:
all text values trimmed; empty text values removed/ignored
multiple text nodes, i.e. when text , other nodes mixed, text stored in array. if there's 1 text value store string.
id attributes used property name if present; otherwise node name used. multiple instances of same node name, no id, stored array (but not demonstrated currently).
like empty text nodes, comment nodes removed/ignored
Comments
Post a Comment