XMLUtils.cpp 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /*
  2. * Copyright (c) 2023, Dan Klishch <danilklishch@gmail.com>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/NonnullOwnPtr.h>
  7. #include <LibXML/DOM/Node.h>
  8. #include "Parser/XMLUtils.h"
  9. namespace JSSpecCompiler {
  10. bool contains_empty_text(XML::Node const* node)
  11. {
  12. return node->as_text().builder.string_view().trim_whitespace().is_empty();
  13. }
  14. Optional<StringView> get_attribute_by_name(XML::Node const* node, StringView attribute_name)
  15. {
  16. auto const& attribute = node->as_element().attributes.get(attribute_name);
  17. if (!attribute.has_value())
  18. return {};
  19. return attribute.value();
  20. }
  21. Optional<StringView> get_text_contents(XML::Node const* node)
  22. {
  23. auto const& children = node->as_element().children;
  24. if (children.size() != 1 || !children[0]->is_text())
  25. return {};
  26. return children[0]->as_text().builder.string_view();
  27. }
  28. Optional<XML::Node const*> get_single_child_with_tag(XML::Node const* element, StringView tag_name)
  29. {
  30. XML::Node const* result = nullptr;
  31. for (auto const& child : element->as_element().children) {
  32. auto is_valid = child->content.visit(
  33. [&](XML::Node::Element const& element) {
  34. result = child;
  35. return result != nullptr || element.name != tag_name;
  36. },
  37. [&](XML::Node::Text const&) {
  38. return contains_empty_text(child);
  39. },
  40. [&](auto const&) { return true; });
  41. if (!is_valid)
  42. return {};
  43. }
  44. if (result == nullptr)
  45. return {};
  46. return result;
  47. }
  48. }