2 using System.Collections.Generic;
7 public class XmlExtractor {
8 public const int EC_BEG = 1; // begin of subtree (current node descends) - in
9 public const int EC_CTN = 2; // continue with next sibling element - in / out: data of found element
10 public const int EC_END = 3; // subtree completion (current node ascends); no data - out
13 private XmlDocument docNode;
14 private bool textMode;
15 public XmlNode CurrentNode;
17 public XmlExtractor(object BaseNode = null, bool TextMode = false) {
18 this.CurrentNode = (XmlNode)BaseNode;
19 this.textMode = TextMode;
22 public void openInput(string input){
23 this.docNode = new XmlDocument();
24 this.docNode.Load(input);
25 this.CurrentNode = this.docNode;
29 this.CurrentNode = this.docNode;
31 public void toParent(){
32 this.CurrentNode = this.CurrentNode.ParentNode;
34 public int extractElement(int extr_ctl, out string elem, out string value, out Dictionary<string,string> attrs) {
37 attrs = new Dictionary<string,string>();
41 if (extr_ctl == EC_BEG) {
42 srh_node = this.CurrentNode.FirstChild;
43 } else if (extr_ctl == EC_CTN) {
44 srh_node = this.CurrentNode.NextSibling;
49 // search for next element node
50 if (! this.textMode) {
51 while (srh_node != null) {
52 if (srh_node.NodeType != XmlNodeType.Element) {
53 srh_node = srh_node.NextSibling;
60 if (srh_node != null) {
61 // element node found: extract tag name, value and attributes
62 this.CurrentNode = srh_node;
63 this.getCurrentNodeData(out elem, out value, out attrs);
66 // terminate / ascend subtree after child extraction
67 if (extr_ctl == EC_CTN) {
68 this.CurrentNode = this.CurrentNode.ParentNode;
74 public void getCurrentNodeData(out string elem, out string value, out Dictionary<string,string> attrs) {
75 elem = this.CurrentNode.Name;
77 attrs = new Dictionary<string,string>();
79 if (this.CurrentNode.NodeType == XmlNodeType.Text) value = this.CurrentNode.Value;
82 if (this.CurrentNode.InnerText != null) value = this.CurrentNode.InnerText;
84 if (this.CurrentNode.Attributes != null) {
85 for (int att_idx = 0; att_idx < this.CurrentNode.Attributes.Count; att_idx++) {
86 var att_node = this.CurrentNode.Attributes[att_idx];
87 attrs[att_node.Name] = this.CurrentNode.Attributes[att_idx].Value;
91 public XmlNode gotoChild(string name) {
92 // return True/False, if child node could be found
96 Dictionary<string,string> attrs;
97 while ((cntl = this.extractElement(cntl, out elem, out value, out attrs)) != EC_END) {
98 if (elem == name) return this.CurrentNode;
102 public XmlNode requireChild(string name) {
103 // throws exception, if child not present
104 XmlNode child = this.gotoChild(name);
105 if (child == null) throw new Exception("Could not find node "+name);