helpers.odin 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package encoding_xml
  2. /*
  3. An XML 1.0 / 1.1 parser
  4. Copyright 2021-2022 Jeroen van Rijn <[email protected]>.
  5. Made available under Odin's BSD-3 license.
  6. This file contains helper functions.
  7. */
  8. // Find parent's nth child with a given ident.
  9. find_child_by_ident :: proc(doc: ^Document, parent_id: Element_ID, ident: string, nth := 0) -> (res: Element_ID, found: bool) {
  10. tag := doc.elements[parent_id]
  11. count := 0
  12. for v in tag.value {
  13. switch child_id in v {
  14. case string: continue
  15. case Element_ID:
  16. child := doc.elements[child_id]
  17. /*
  18. Skip commments. They have no name.
  19. */
  20. if child.kind != .Element { continue }
  21. /*
  22. If the ident matches and it's the nth such child, return it.
  23. */
  24. if child.ident == ident {
  25. if count == nth { return child_id, true }
  26. count += 1
  27. }
  28. }
  29. }
  30. return 0, false
  31. }
  32. // Find an attribute by key.
  33. find_attribute_val_by_key :: proc(doc: ^Document, parent_id: Element_ID, key: string) -> (val: string, found: bool) {
  34. tag := doc.elements[parent_id]
  35. for attr in tag.attribs {
  36. /*
  37. If the ident matches, we're done. There can only ever be one attribute with the same name.
  38. */
  39. if attr.key == key { return attr.val, true }
  40. }
  41. return "", false
  42. }