Xml.ts 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. export type IXmlAttribute = Attr;
  2. export class IXmlElement {
  3. public name: string;
  4. public value: string;
  5. public hasAttributes: boolean = false;
  6. public firstAttribute: IXmlAttribute;
  7. public hasElements: boolean;
  8. private attrs: IXmlAttribute[];
  9. private elem: Element;
  10. constructor(elem: Element) {
  11. this.elem = elem;
  12. this.name = elem.nodeName.toLowerCase();
  13. if (elem.hasAttributes()) {
  14. this.hasAttributes = true;
  15. this.firstAttribute = elem.attributes[0];
  16. }
  17. this.hasElements = elem.hasChildNodes();
  18. // Look for a value
  19. if (elem.childNodes.length === 1 && elem.childNodes[0].nodeType === Node.TEXT_NODE) {
  20. this.value = elem.childNodes[0].nodeValue;
  21. }
  22. }
  23. public attribute(attributeName: string): IXmlAttribute {
  24. return this.elem.attributes.getNamedItem(attributeName);
  25. }
  26. public attributes(): IXmlAttribute[] {
  27. if (typeof this.attrs === "undefined") {
  28. let attributes: NamedNodeMap = this.elem.attributes;
  29. let attrs: IXmlAttribute[] = [];
  30. for (let i: number = 0; i < attributes.length; i += 1) {
  31. attrs.push(attributes[i]);
  32. }
  33. this.attrs = attrs;
  34. }
  35. return this.attrs;
  36. }
  37. public element(elementName: string): IXmlElement {
  38. return this.elements(elementName)[0];
  39. }
  40. public elements(nodeName?: string): IXmlElement[] {
  41. let nodes: NodeList = this.elem.childNodes;
  42. let ret: IXmlElement[] = [];
  43. let nameUnset: boolean = nodeName === undefined;
  44. if (!nameUnset) {
  45. nodeName = nodeName.toLowerCase();
  46. }
  47. // console.log("-", nodeName, nodes.length, this.elem.childElementCount, this.elem.getElementsByTagName(nodeName).length);
  48. // if (nodeName === "measure") {
  49. // console.log(this.elem);
  50. // }
  51. for (let i: number = 0; i < nodes.length; i += 1) {
  52. let node: Node = nodes[i];
  53. // console.log("node: ", this.elem.nodeName, ">>", node.nodeName, node.nodeType === Node.ELEMENT_NODE);
  54. if (node.nodeType === Node.ELEMENT_NODE &&
  55. (nameUnset || node.nodeName.toLowerCase() === nodeName)) {
  56. ret.push(new IXmlElement(node as Element));
  57. }
  58. }
  59. return ret;
  60. }
  61. }