helpers.odin 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. /*
  2. An XML 1.0 / 1.1 parser
  3. Copyright 2021-2022 Jeroen van Rijn <[email protected]>.
  4. Made available under Odin's BSD-3 license.
  5. This file contains helper functions.
  6. */
  7. package xml
  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. }