]>
git.kaiwu.me - njs.git/commit
XML: added XMLNode API to modify XML documents.
- delete node.$attr$a is a shorthand syntax for
node.removeAttribute('a')
- node.removeAllAttributes() removes all attributes of the node.
- node.removeAttribute(attr_name) removes attribute named
attr_name.
- node.setAttribute(attr_name, value || null) sets a value for an
attr_name. When value is null attribute named attr_name is
deleted.
- node.$attr$a = 'xxx' is a shorthand syntax for
node.setAttribute('a', 'xxx');
- The methods and operations below make copy-on-write
changes to the original XML parsed document.
For example:
var doc = xml.parse(<r><a><b/></a></r>);
var b = doc.$root.a.b;
doc.$root.removeAllChildren();
console.log((new TextDecoder()).decode(xml.c14n(doc))); /* <r></r> */
console.log(b); /* XMLNode {$name:'b'} */
console.log(b.$parent); /* XMLNode {$name:'a',$tags:[XMLNode
{$name:'b'}] */
"b" is valid after removeAllChildren() call, but is not a part
of the document tree anymore.
- node.addChild(nd) adds XMLNode as a child to node.
nd recursively copied before adding to the node.
- node.removeChildren(tag_name?) removes all the children tags
named tag_name. If tag_name is absent all children tags are
removed.
- node.removeText() removes the node's text value.
- node.setText(string || null) sets a text value for the node.
When value is null the node's text is deleted.
- node.$tags = [node1, node2, ..] is a shorthand syntax for
node.removeChildren();
node.addChild(node1);
node.addChild(node2)
- node.$text = 'xxx' is a shorthand syntax for
node.setText('xxx');
In addition the following method were added:
- xml.serialize() is the same as xml.c14n()
- xml.serializeToString() is the same as xml.c14n()
except it returns the result as string.
Example:
const xml = require("xml");
let data = `<note><to b="bar" a="foo">Tove</to><from>Jani</from></note>`;
let doc = xml.parse(data);
doc.$root.to.$attr$b = 'bar2';
doc.$root.to.setAttribute('c', 'baz');
delete doc.$root.to.$attr$a;
console.log(xml.serializeToString(doc.$root.to)) /* '<to b="bar2" c="baz">Tove</to>' */
doc.$root.to.removeAllAttributes();
doc.$root.from.$text = 'Jani2';
console.log(xml.serializeToString(doc)) /* '<note><to>Tove</to><from>Jani2</from></note>' */
doc.$root.to.$tags = [xml.parse(`<a/>`), xml.parse(`<b/>`)];
doc.$root.to.addChild(xml.parse(`<a/>`));
console.log(xml.serializeToString(doc.$root.to)) /* '<to><a></a><b></b><a></a></to>' */
doc.$root.to.removeChildren('a');
console.log(xml.serializeToString(doc.$root.to)) /* '<to><b></b></to>' */