1 /**
2  * Useful ae.utils.xml helpers
3  *
4  * License:
5  *   This Source Code Form is subject to the terms of
6  *   the Mozilla Public License, v. 2.0. If a copy of
7  *   the MPL was not distributed with this file, You
8  *   can obtain one at http://mozilla.org/MPL/2.0/.
9  *
10  * Authors:
11  *   Vladimir Panteleev <vladimir@thecybershadow.net>
12  */
13 
14 module ae.utils.xml.helpers;
15 
16 import std.algorithm.iteration;
17 import std.array;
18 
19 import ae.utils.xml.lite;
20 
21 bool isTag(XmlNode n, string tag, XmlNodeType type = XmlNodeType.Node)
22 {
23 	return n.type == type && n.tag ==  tag;
24 }
25 
26 XmlNode findOnlyChild(XmlNode n, string tag, XmlNodeType type = XmlNodeType.Node)
27 {
28 	return n.isTag(tag, type) ? n :
29 		n.children.length != 1 ? null :
30 		n.children[0].findOnlyChild(tag, type);
31 }
32 
33 XmlNode findOnlyChild(XmlNode n, XmlNodeType type)
34 {
35 	return n.type == type ? n :
36 		n.children.length != 1 ? null :
37 		n.children[0].findOnlyChild(type);
38 }
39 
40 XmlNode[] findNodes(XmlNode n, string tag)
41 {
42 	if (n.isTag(tag))
43 		return [n];
44 	return n.children.map!(n => findNodes(n, tag)).join;
45 }
46 
47 XmlNode newNode(XmlNodeType type, string tag, string[string] attributes = null, XmlNode[] children = null)
48 {
49 	auto node = new XmlNode(type, tag);
50 	node.attributes = attributes;
51 	node.children = children;
52 	return node;
53 }
54 
55 XmlNode newNode(string tag, string[string] attributes = null, XmlNode[] children = null)
56 {
57 	return newNode(XmlNodeType.Node, tag, attributes, children);
58 }
59 
60 XmlNode newTextNode(string text)
61 {
62 	return newNode(XmlNodeType.Text, text);
63 }