/
document.js
96 lines (78 loc) · 2.55 KB
/
document.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
var bindings = require('./bindings');
var Element = require('./element');
/// Create a new document
/// @param {string} version xml version, default 1.0
/// @param {string} encoding the encoding, default utf8
/// @constructor
var Document = function(version, encoding) {
version = version || '1.0';
var doc = new bindings.Document(version);
doc.encoding(encoding || 'utf8');
return doc;
};
Document.prototype = bindings.Document.prototype;
/// get or set the root element
/// if called without any arguments, this will return the document root
/// @param {Element} [elem] if specified, this will become the new document root
Document.prototype.root = function(elem) {
return this._root(elem);
};
/// add a child node to the document
/// this will set the document root
Document.prototype.node = function(name, content) {
return this.root(Element(this, name, content));
};
/// xpath search
/// @return array of matching elements
Document.prototype.find = function(xpath, ns_uri) {
return this.root().find(xpath, ns_uri);
};
/// xpath search
/// @return first element matching
Document.prototype.get = function(xpath, ns_uri) {
return this.root().get(xpath, ns_uri);
};
/// @return a given child
Document.prototype.child = function(id) {
if (id === undefined || typeof id !== 'number') {
throw new Error('id argument required for #child');
}
return this.root().child(id);
};
/// @return an Array of child nodes of the document root
Document.prototype.childNodes = function() {
return this.root().childNodes();
};
/// @return a string representation of the document
Document.prototype.toString = function() {
return this._toString();
}
/// @return the document version
Document.prototype.version = function() {
return this._version();
}
/// @return the document encoding
Document.prototype.encoding = function(encoding) {
return this._encoding(encoding);
}
/// @return whether the XmlDocument is valid
Document.prototype.validate = function(xsd) {
return this._validate(xsd);
}
/// @return array of namespaces in document
Document.prototype.namespaces = function() {
return this.root().namespaces();
};
module.exports = Document;
/// parse a string into a html document
/// @param string html string to parse
/// @return a Document
module.exports.fromHtmlString = function(string) {
return bindings.fromHtmlString(string);
}
/// parse a string into a xml document
/// @param string xml string to parse
/// @return a Document
module.exports.fromXmlString = function(string) {
return bindings.fromXmlString(string);
}