rxerces 0.7.0 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: b67969a411b4eb67c0eef75b5c32496a39f962fc8f1b67015eeaf8cb20555d21
4
- data.tar.gz: 3597880bb07a892766f5717d979cc140416f28e4db5d92b562b173e3f3ec4027
3
+ metadata.gz: 11b8eb0e073b6b5c956a5f923c4c131932fd9e3c4d87dca5f7e22937b2020979
4
+ data.tar.gz: f120e76361bbc1869643a4cc13dc706d24d6a5a3649f22dab5e6151b6950b780
5
5
  SHA512:
6
- metadata.gz: e7fa8c0ca9ace56ea3ec1f070340ae11ffa92e2090220099c5a7e7a25e069973ebc85fabbdda120f94dd59fdd1ad72cdbb16f735f48fea77d1dccadb0c7ee27d
7
- data.tar.gz: 66b6e8eceb35d815b9fa08dfbb0581a3561891ec9f47976386188f3bac207470db7cb97ea9f9688eab13e7288cde2ff9784dcc5e604dc33d092af0ea12c28512
6
+ metadata.gz: 32aa560c5376d96ab76b6301b1b25b7dd635f4525b744d50cd28769d500b79ba4b809a0c67a18b025d0a1b42ea36f41710de96e65cdbb10bc67680e7c46e24f0
7
+ data.tar.gz: 988f21419ae4f72611fa4cf5367a92eeb40b93d2adc668eeb0e7bf613c425a18103ba754ebdfe9d1c939686b94cbde6fd21c2aa76774053149511133906748d6
checksums.yaml.gz.sig CHANGED
Binary file
data/CHANGES.md CHANGED
@@ -1,3 +1,9 @@
1
+ ## 0.7.1 - 22-Nov-2026
2
+ * Improved native DOM traversal and serialization performance.
3
+ * Reduced XPath overhead with reusable Xalan contexts and compiled expression caching.
4
+ * Document serialization now returns UTF-8 with a matching XML encoding declaration.
5
+ * Path fix for FreeBSD.
6
+
1
7
  ## 0.7.0 - 3-Jan-2026
2
8
  * Added XPath validation to prevent XPath injection attacks, with checks for
3
9
  unbalanced quotes, dangerous functions, encoded characters, and injection patterns.
data/Rakefile CHANGED
@@ -11,7 +11,8 @@ CLEAN.include(
11
11
  '**/*.log', # Ruby extension build log
12
12
  '**/*.lock', # Gemfile.lock
13
13
  '**/Makefile', # C Makefile
14
- '**/conftest.dSYM', # OS X build directory
14
+ '**/*.dSYM', # OS X build directory
15
+ 'tmp/', # AI probably uses this
15
16
  "**/*.#{CONFIG['DLEXT']}" # C shared object
16
17
  )
17
18
 
data/benchmarks/README.md CHANGED
@@ -28,6 +28,33 @@ Or run a specific benchmark:
28
28
  ruby benchmarks/parse_benchmark.rb
29
29
  ```
30
30
 
31
+ For a dependency-free benchmark of the native bindings, run:
32
+
33
+ ```bash
34
+ bundle exec rake compile
35
+ ruby benchmarks/bindings_benchmark.rb > bindings-results.json
36
+ ```
37
+
38
+ This reports median time per call and Ruby object allocations for parsing,
39
+ traversal, XPath, text extraction, and serialization at 100, 1,000, and 10,000
40
+ elements. It loads the extension from this checkout. Compare results using the
41
+ same Ruby, native libraries, and machine; set `BENCH_TIME=1` for longer samples.
42
+ Ruby allocation counts exclude memory allocated by Xerces and Xalan.
43
+
44
+ The sibling traversal optimization changes `children` and `element_children`
45
+ from repeated indexed DOM lookups to a single sibling walk. In a local Ruby
46
+ 4.0.10/macOS run with Xalan enabled, accessing 10,000 children dropped from about
47
+ 2.8 seconds to 1 millisecond. At 1,000 elements, serialization dropped from
48
+ 298 to 238 microseconds. These are microbenchmark results, not application-wide
49
+ speedups. Parsing improved only slightly, and a separate repeated comparison
50
+ found full XPath query times roughly unchanged.
51
+
52
+ First/last element access now starts from the appropriate end without counting
53
+ all siblings. Xerces-only first-match XPath/CSS queries also avoid allocating
54
+ Ruby wrappers for the remaining matches; the native XPath snapshot still
55
+ contains all matches. Document serialization now writes UTF-8 bytes directly,
56
+ returns a UTF-8 Ruby string, and declares UTF-8 in the XML output.
57
+
31
58
  ## Benchmark Categories
32
59
 
33
60
  ### 1. Parse Benchmark (`parse_benchmark.rb`)
@@ -62,7 +89,7 @@ Tests document serialization (`to_s`/`to_xml`) with various document sizes.
62
89
 
63
90
  ## Notes
64
91
 
65
- - All benchmarks use `benchmark-ips` for accurate iterations-per-second measurements
66
- - Each benchmark runs with a 2-second warmup and 5-second measurement period
92
+ - The comparison benchmarks use `benchmark-ips` with a 2-second warmup and 5-second measurement period
93
+ - `bindings_benchmark.rb` uses Ruby's standard library and three timed samples per operation
67
94
  - Nokogiri and Ox tests are skipped if not installed
68
95
  - RXerces requires Xalan-C for full XPath 1.0 support (CSS selectors need XPath)
@@ -0,0 +1,53 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ # Dependency-free benchmark for overhead in the Ruby bindings. Run against the
5
+ # same Ruby and Xerces builds before and after a change; compare median times.
6
+ $LOAD_PATH.unshift File.expand_path('../lib', __dir__)
7
+ require 'rxerces'
8
+ require 'benchmark'
9
+ require 'json'
10
+
11
+ duration = Float(ENV.fetch('BENCH_TIME', '0.1'))
12
+ raise 'BENCH_TIME must be positive' unless duration.positive? && duration.finite?
13
+
14
+ results = { ruby: RUBY_DESCRIPTION, xalan: RXerces.xalan_enabled?, measurements: [] }
15
+ [100, 1_000, 10_000].each do |count|
16
+ xml = "<root>#{'<item id="1"><name>Hello</name></item>' * count}</root>"
17
+ doc = RXerces.XML(xml)
18
+ root = doc.root
19
+ operations = {
20
+ parse: -> { RXerces.XML(xml) },
21
+ children: -> { root.children },
22
+ element_children: -> { root.element_children },
23
+ first_element_child: -> { root.first_element_child },
24
+ last_element_child: -> { root.last_element_child },
25
+ xpath: -> { doc.xpath('//item') },
26
+ at_xpath: -> { doc.at_xpath('//item') },
27
+ text: -> { root.text },
28
+ serialize: -> { doc.to_xml }
29
+ }
30
+
31
+ operations.each do |name, operation|
32
+ operation.call # Warm lazy initialization and expression caches.
33
+ iterations = 1
34
+ loop do
35
+ elapsed = Benchmark.realtime { iterations.times { operation.call } }
36
+ break if elapsed >= duration
37
+ iterations *= 2
38
+ end
39
+ samples = Array.new(3) do
40
+ GC.start
41
+ Benchmark.realtime { iterations.times { operation.call } } / iterations
42
+ end
43
+ GC.start
44
+ allocated = GC.stat(:total_allocated_objects)
45
+ operation.call
46
+ allocated = GC.stat(:total_allocated_objects) - allocated
47
+ results[:measurements] << {
48
+ elements: count, operation: name, microseconds: samples.sort[1] * 1_000_000,
49
+ ruby_allocations: allocated
50
+ }
51
+ end
52
+ end
53
+ puts JSON.pretty_generate(results)
@@ -3,6 +3,12 @@ require 'mkmf'
3
3
  # Force C++ compiler for the extension
4
4
  $CXXFLAGS << " -std=c++11"
5
5
 
6
+ # Some Ruby builds omit optflags from CXXFLAGS. Use Ruby's optimization flags
7
+ # in that case, while preserving an explicit choice (including -O0).
8
+ unless $CXXFLAGS.match?(/(?:\A|\s)-O\S*/)
9
+ $CXXFLAGS << " #{RbConfig::CONFIG['optflags']}"
10
+ end
11
+
6
12
  # Try to find Xerces-C via homebrew on macOS
7
13
  if RUBY_PLATFORM =~ /darwin/
8
14
  homebrew_prefix = `brew --prefix xerces-c 2>/dev/null`.chomp
@@ -12,6 +18,11 @@ if RUBY_PLATFORM =~ /darwin/
12
18
  end
13
19
  end
14
20
 
21
+ if RUBY_PLATFORM =~ /bsd/
22
+ $INCFLAGS << " -I/usr/local/include"
23
+ $LDFLAGS << " -L/usr/local/lib"
24
+ end
25
+
15
26
  # Check for Xerces-C library
16
27
  unless have_library('xerces-c')
17
28
  puts "Xerces-C library not found. Please install it:"
@@ -18,6 +18,7 @@
18
18
  #include <mutex>
19
19
  #include <list>
20
20
  #include <unordered_map>
21
+ #include <memory>
21
22
 
22
23
  #ifdef HAVE_XALAN
23
24
  #include <xalanc/XPath/XPathEvaluator.hpp>
@@ -68,6 +69,53 @@ static bool cache_xpath_validation = true; // Default: enabled
68
69
  static size_t xpath_cache_max_size = 10000; // Max cached expressions
69
70
  static size_t xpath_max_length = 10000; // Max XPath expression length
70
71
 
72
+ #ifdef HAVE_XALAN
73
+ // Cached Xalan context per document for XPath performance
74
+ // This avoids recreating expensive Xalan infrastructure on every XPath query
75
+ struct XalanContext {
76
+ XercesParserLiaison* liaison;
77
+ XercesDOMSupport* domSupport;
78
+ XalanDocument* xalanDoc;
79
+ XercesDocumentWrapper* docWrapper;
80
+ XPathEnvSupportDefault* envSupport;
81
+ XObjectFactoryDefault* objectFactory;
82
+ XPathExecutionContextDefault* executionContext;
83
+ XPathConstructionContextDefault* constructionContext;
84
+ XPathFactoryDefault* factory;
85
+ XPathProcessorImpl* processor;
86
+
87
+ XalanContext() : liaison(nullptr), domSupport(nullptr), xalanDoc(nullptr),
88
+ docWrapper(nullptr), envSupport(nullptr), objectFactory(nullptr),
89
+ executionContext(nullptr), constructionContext(nullptr),
90
+ factory(nullptr), processor(nullptr) {}
91
+
92
+ ~XalanContext() {
93
+ // Clean up in reverse order of creation
94
+ delete executionContext;
95
+ delete constructionContext;
96
+ delete objectFactory;
97
+ delete envSupport;
98
+ delete factory;
99
+ delete processor;
100
+ // domSupport must be deleted before liaison
101
+ delete domSupport;
102
+ // liaison owns xalanDoc/docWrapper, so don't delete them separately
103
+ delete liaison;
104
+ }
105
+ };
106
+
107
+ // Compiled XPath expression cache per document
108
+ struct CompiledXPath {
109
+ XPath* xpath;
110
+ std::string expression;
111
+
112
+ CompiledXPath(XPath* x, const std::string& expr) : xpath(x), expression(expr) {}
113
+ };
114
+
115
+ // LRU cache for compiled XPath expressions
116
+ static const size_t XPATH_COMPILE_CACHE_SIZE = 100;
117
+ #endif
118
+
71
119
  // Forward declarations
72
120
  static std::string css_to_xpath(const char* css);
73
121
  static VALUE node_css(VALUE self, VALUE selector);
@@ -328,11 +376,23 @@ private:
328
376
  char* fLocalForm;
329
377
  };
330
378
 
379
+ // DOM objects use release(), rather than delete, for cleanup.
380
+ struct DOMRelease {
381
+ template <typename T> void operator()(T* object) const {
382
+ if (object) object->release();
383
+ }
384
+ };
385
+
331
386
  // Wrapper structure for DOMDocument
332
387
  typedef struct {
333
388
  DOMDocument* doc;
334
389
  XercesDOMParser* parser;
335
390
  std::vector<std::string>* parse_errors;
391
+ #ifdef HAVE_XALAN
392
+ XalanContext* xalan_context; // Cached Xalan context for XPath performance
393
+ std::list<CompiledXPath*>* xpath_cache_list; // LRU list of compiled expressions
394
+ std::unordered_map<std::string, std::list<CompiledXPath*>::iterator>* xpath_cache_map;
395
+ #endif
336
396
  } DocumentWrapper;
337
397
 
338
398
  // Wrapper structure for DOMNode
@@ -447,6 +507,25 @@ public:
447
507
  static void document_free(void* ptr) {
448
508
  DocumentWrapper* wrapper = (DocumentWrapper*)ptr;
449
509
  if (wrapper) {
510
+ #ifdef HAVE_XALAN
511
+ // Clean up XPath cache first
512
+ if (wrapper->xpath_cache_list) {
513
+ for (auto& compiled : *wrapper->xpath_cache_list) {
514
+ if (compiled && compiled->xpath && wrapper->xalan_context && wrapper->xalan_context->factory) {
515
+ wrapper->xalan_context->factory->returnObject(compiled->xpath);
516
+ }
517
+ delete compiled;
518
+ }
519
+ delete wrapper->xpath_cache_list;
520
+ }
521
+ if (wrapper->xpath_cache_map) {
522
+ delete wrapper->xpath_cache_map;
523
+ }
524
+ // Clean up Xalan context
525
+ if (wrapper->xalan_context) {
526
+ delete wrapper->xalan_context;
527
+ }
528
+ #endif
450
529
  if (wrapper->parser) {
451
530
  delete wrapper->parser;
452
531
  }
@@ -661,7 +740,10 @@ static VALUE document_parse(int argc, VALUE* argv, VALUE klass) {
661
740
  parser->setErrorHandler(&error_handler);
662
741
 
663
742
  try {
664
- MemBufInputSource input((const XMLByte*)xml_str, strlen(xml_str), "memory");
743
+ MemBufInputSource input((const XMLByte*)xml_str, RSTRING_LEN(str), "memory");
744
+ // Parsing is synchronous and holds the GVL, so the Ruby string stays
745
+ // valid until the stream is finished. Avoid copying the entire input.
746
+ input.setCopyBufToStream(false);
665
747
  parser->parse(input);
666
748
 
667
749
  DOMDocument* doc = parser->getDocument();
@@ -670,6 +752,11 @@ static VALUE document_parse(int argc, VALUE* argv, VALUE klass) {
670
752
  wrapper->doc = doc;
671
753
  wrapper->parser = parser;
672
754
  wrapper->parse_errors = parse_errors;
755
+ #ifdef HAVE_XALAN
756
+ wrapper->xalan_context = nullptr; // Lazily initialized on first XPath query
757
+ wrapper->xpath_cache_list = nullptr;
758
+ wrapper->xpath_cache_map = nullptr;
759
+ #endif
673
760
 
674
761
  VALUE rb_doc = TypedData_Wrap_Struct(rb_cDocument, &document_type, wrapper);
675
762
 
@@ -743,17 +830,20 @@ static VALUE document_to_s(VALUE self) {
743
830
 
744
831
  try {
745
832
  DOMImplementation* impl = DOMImplementationRegistry::getDOMImplementation(XStr("LS").unicodeForm());
746
- DOMLSSerializer* serializer = ((DOMImplementationLS*)impl)->createLSSerializer();
747
-
748
- XMLCh* xml_str = serializer->writeToString(wrapper->doc);
749
- CharStr utf8_str(xml_str);
750
-
751
- VALUE result = rb_str_new_cstr(utf8_str.localForm());
752
-
753
- XMLString::release(&xml_str);
754
- serializer->release();
833
+ MemBufFormatTarget target;
834
+ std::unique_ptr<DOMLSSerializer, DOMRelease> serializer(
835
+ ((DOMImplementationLS*)impl)->createLSSerializer());
836
+ std::unique_ptr<DOMLSOutput, DOMRelease> output(
837
+ ((DOMImplementationLS*)impl)->createLSOutput());
838
+ output->setEncoding(XStr("UTF-8").unicodeForm());
839
+ output->setByteStream(&target);
755
840
 
756
- return result;
841
+ // Write UTF-8 bytes directly instead of allocating a UTF-16 document
842
+ // string, transcoding it back to bytes, and scanning for its length.
843
+ serializer->write(wrapper->doc, output.get());
844
+ output.reset();
845
+ serializer.reset();
846
+ return rb_utf8_str_new((const char*)target.getRawBuffer(), target.getLen());
757
847
  } catch (const DOMException& e) {
758
848
  CharStr message(e.getMessage());
759
849
  rb_raise(rb_eRuntimeError, "Failed to serialize document: %s", message.localForm());
@@ -890,17 +980,17 @@ static VALUE document_children(VALUE self) {
890
980
  DocumentWrapper* wrapper;
891
981
  TypedData_Get_Struct(self, DocumentWrapper, &document_type, wrapper);
892
982
 
893
- VALUE children = rb_ary_new();
894
-
895
983
  if (!wrapper->doc) {
896
- return children;
984
+ return rb_ary_new();
897
985
  }
898
986
 
899
987
  DOMNodeList* child_nodes = wrapper->doc->getChildNodes();
900
988
  XMLSize_t count = child_nodes->getLength();
901
989
 
902
- for (XMLSize_t i = 0; i < count; i++) {
903
- DOMNode* child = child_nodes->item(i);
990
+ // Pre-size array for better performance
991
+ VALUE children = rb_ary_new_capa((long)count);
992
+
993
+ for (DOMNode* child = wrapper->doc->getFirstChild(); child; child = child->getNextSibling()) {
904
994
  rb_ary_push(children, wrap_node(child, self));
905
995
  }
906
996
 
@@ -912,17 +1002,17 @@ static VALUE document_element_children(VALUE self) {
912
1002
  DocumentWrapper* wrapper;
913
1003
  TypedData_Get_Struct(self, DocumentWrapper, &document_type, wrapper);
914
1004
 
915
- VALUE children = rb_ary_new();
916
-
917
1005
  if (!wrapper->doc) {
918
- return children;
1006
+ return rb_ary_new();
919
1007
  }
920
1008
 
921
1009
  DOMNodeList* child_nodes = wrapper->doc->getChildNodes();
922
1010
  XMLSize_t count = child_nodes->getLength();
923
1011
 
924
- for (XMLSize_t i = 0; i < count; i++) {
925
- DOMNode* child = child_nodes->item(i);
1012
+ // Pre-size array (may be smaller than count, but good estimate)
1013
+ VALUE children = rb_ary_new_capa((long)count);
1014
+
1015
+ for (DOMNode* child = wrapper->doc->getFirstChild(); child; child = child->getNextSibling()) {
926
1016
  if (child->getNodeType() == DOMNode::ELEMENT_NODE) {
927
1017
  rb_ary_push(children, wrap_node(child, self));
928
1018
  }
@@ -931,6 +1021,18 @@ static VALUE document_element_children(VALUE self) {
931
1021
  return children;
932
1022
  }
933
1023
 
1024
+ // Shared endpoint traversal for document and node element access.
1025
+ static VALUE element_child(DOMNode* parent, VALUE doc_ref, bool last) {
1026
+ // Walk from the requested end without counting all siblings first.
1027
+ for (DOMNode* child = last ? parent->getLastChild() : parent->getFirstChild();
1028
+ child; child = last ? child->getPreviousSibling() : child->getNextSibling()) {
1029
+ if (child->getNodeType() == DOMNode::ELEMENT_NODE) {
1030
+ return wrap_node(child, doc_ref);
1031
+ }
1032
+ }
1033
+ return Qnil;
1034
+ }
1035
+
934
1036
  // document.first_element_child - returns first element child
935
1037
  static VALUE document_first_element_child(VALUE self) {
936
1038
  DocumentWrapper* wrapper;
@@ -940,17 +1042,7 @@ static VALUE document_first_element_child(VALUE self) {
940
1042
  return Qnil;
941
1043
  }
942
1044
 
943
- DOMNodeList* child_nodes = wrapper->doc->getChildNodes();
944
- XMLSize_t count = child_nodes->getLength();
945
-
946
- for (XMLSize_t i = 0; i < count; i++) {
947
- DOMNode* child = child_nodes->item(i);
948
- if (child->getNodeType() == DOMNode::ELEMENT_NODE) {
949
- return wrap_node(child, self);
950
- }
951
- }
952
-
953
- return Qnil;
1045
+ return element_child(wrapper->doc, self, false);
954
1046
  }
955
1047
 
956
1048
  // document.last_element_child - returns last element child
@@ -962,22 +1054,92 @@ static VALUE document_last_element_child(VALUE self) {
962
1054
  return Qnil;
963
1055
  }
964
1056
 
965
- DOMNodeList* child_nodes = wrapper->doc->getChildNodes();
966
- XMLSize_t count = child_nodes->getLength();
1057
+ return element_child(wrapper->doc, self, true);
1058
+ }
967
1059
 
968
- // Search backwards for last element
969
- for (XMLSize_t i = count; i > 0; i--) {
970
- DOMNode* child = child_nodes->item(i - 1);
971
- if (child->getNodeType() == DOMNode::ELEMENT_NODE) {
972
- return wrap_node(child, self);
1060
+ #ifdef HAVE_XALAN
1061
+ // Helper to initialize or get cached Xalan context for a document
1062
+ static XalanContext* get_or_create_xalan_context(DocumentWrapper* doc_wrapper) {
1063
+ if (doc_wrapper->xalan_context) {
1064
+ return doc_wrapper->xalan_context;
1065
+ }
1066
+
1067
+ // Create new context
1068
+ XalanContext* ctx = new XalanContext();
1069
+
1070
+ try {
1071
+ ctx->liaison = new XercesParserLiaison();
1072
+ ctx->domSupport = new XercesDOMSupport(*ctx->liaison);
1073
+
1074
+ // Create Xalan document wrapper - this is owned by liaison
1075
+ ctx->xalanDoc = ctx->liaison->createDocument(doc_wrapper->doc, false, false, false);
1076
+ if (!ctx->xalanDoc) {
1077
+ delete ctx;
1078
+ return nullptr;
973
1079
  }
1080
+ ctx->docWrapper = static_cast<XercesDocumentWrapper*>(ctx->xalanDoc);
1081
+
1082
+ // Create XPath infrastructure
1083
+ ctx->envSupport = new XPathEnvSupportDefault();
1084
+ ctx->objectFactory = new XObjectFactoryDefault();
1085
+ ctx->executionContext = new XPathExecutionContextDefault(*ctx->envSupport, *ctx->domSupport, *ctx->objectFactory);
1086
+ ctx->constructionContext = new XPathConstructionContextDefault();
1087
+ ctx->factory = new XPathFactoryDefault();
1088
+ ctx->processor = new XPathProcessorImpl();
1089
+
1090
+ doc_wrapper->xalan_context = ctx;
1091
+
1092
+ // Initialize XPath expression cache
1093
+ doc_wrapper->xpath_cache_list = new std::list<CompiledXPath*>();
1094
+ doc_wrapper->xpath_cache_map = new std::unordered_map<std::string, std::list<CompiledXPath*>::iterator>();
1095
+
1096
+ return ctx;
1097
+ } catch (...) {
1098
+ delete ctx;
1099
+ return nullptr;
974
1100
  }
1101
+ }
975
1102
 
976
- return Qnil;
1103
+ // Get or compile XPath expression with LRU caching
1104
+ static XPath* get_or_compile_xpath(DocumentWrapper* doc_wrapper, XalanContext* ctx, const char* xpath_str) {
1105
+ std::string expr(xpath_str);
1106
+
1107
+ // Check cache
1108
+ auto it = doc_wrapper->xpath_cache_map->find(expr);
1109
+ if (it != doc_wrapper->xpath_cache_map->end()) {
1110
+ // Splicing preserves the iterator and avoids allocating a list entry.
1111
+ doc_wrapper->xpath_cache_list->splice(doc_wrapper->xpath_cache_list->begin(),
1112
+ *doc_wrapper->xpath_cache_list, it->second);
1113
+ return (*(it->second))->xpath;
1114
+ }
1115
+
1116
+ // Cache miss - compile new XPath
1117
+ XPath* xpath = ctx->factory->create();
1118
+
1119
+ // Get document element for resolver (can be null, that's ok)
1120
+ XalanElement* docElem = ctx->docWrapper->getDocumentElement();
1121
+ ElementPrefixResolverProxy resolver(docElem, *ctx->envSupport, *ctx->domSupport);
1122
+ ctx->processor->initXPath(*xpath, *ctx->constructionContext, XalanDOMString(xpath_str), resolver);
1123
+
1124
+ // Add to cache
1125
+ CompiledXPath* compiled = new CompiledXPath(xpath, expr);
1126
+ doc_wrapper->xpath_cache_list->push_front(compiled);
1127
+ (*doc_wrapper->xpath_cache_map)[expr] = doc_wrapper->xpath_cache_list->begin();
1128
+
1129
+ // Evict if cache is too large
1130
+ if (doc_wrapper->xpath_cache_list->size() > XPATH_COMPILE_CACHE_SIZE) {
1131
+ CompiledXPath* lru = doc_wrapper->xpath_cache_list->back();
1132
+ doc_wrapper->xpath_cache_map->erase(lru->expression);
1133
+ ctx->factory->returnObject(lru->xpath);
1134
+ delete lru;
1135
+ doc_wrapper->xpath_cache_list->pop_back();
1136
+ }
1137
+
1138
+ return xpath;
977
1139
  }
978
1140
 
979
- #ifdef HAVE_XALAN
980
1141
  // Helper function to execute XPath using Xalan for full XPath 1.0 support
1142
+ // Uses cached Xalan context and compiled XPath expressions for performance
981
1143
  static VALUE execute_xpath_with_xalan(DOMNode* context_node, const char* xpath_str, VALUE doc_ref) {
982
1144
  // Validate XPath expression before execution
983
1145
  validate_xpath_expression(xpath_str);
@@ -985,54 +1147,41 @@ static VALUE execute_xpath_with_xalan(DOMNode* context_node, const char* xpath_s
985
1147
  ensure_xerces_initialized();
986
1148
 
987
1149
  try {
988
- // Get the document
989
- DOMDocument* domDoc = context_node->getOwnerDocument();
990
- if (!domDoc && context_node->getNodeType() == DOMNode::DOCUMENT_NODE) {
991
- domDoc = static_cast<DOMDocument*>(context_node);
992
- }
1150
+ // Get the document wrapper
1151
+ DocumentWrapper* doc_wrapper;
1152
+ TypedData_Get_Struct(doc_ref, DocumentWrapper, &document_type, doc_wrapper);
993
1153
 
1154
+ DOMDocument* domDoc = doc_wrapper->doc;
994
1155
  if (!domDoc) {
995
1156
  NodeSetWrapper* wrapper = ALLOC(NodeSetWrapper);
996
1157
  wrapper->nodes_array = rb_ary_new();
997
1158
  return TypedData_Wrap_Struct(rb_cNodeSet, &nodeset_type, wrapper);
998
1159
  }
999
1160
 
1000
- // Create Xalan support objects
1001
- XercesParserLiaison liaison;
1002
- XercesDOMSupport domSupport(liaison);
1003
-
1004
- // Create Xalan document - this creates and returns a XercesDocumentWrapper
1005
- XalanDocument* xalanDoc = liaison.createDocument(domDoc, false, false, false);
1006
- if (!xalanDoc) {
1007
- rb_raise(rb_eRuntimeError, "Failed to create Xalan document wrapper");
1161
+ // Get or create cached Xalan context
1162
+ XalanContext* ctx = get_or_create_xalan_context(doc_wrapper);
1163
+ if (!ctx) {
1164
+ rb_raise(rb_eRuntimeError, "Failed to create Xalan context");
1008
1165
  }
1009
1166
 
1010
- // The document IS the wrapper
1011
- XercesDocumentWrapper* docWrapper = static_cast<XercesDocumentWrapper*>(xalanDoc);
1012
-
1013
1167
  // Map the context node to Xalan
1014
- XalanNode* xalanContextNode = docWrapper->mapNode(context_node);
1168
+ XalanNode* xalanContextNode = ctx->docWrapper->mapNode(context_node);
1015
1169
  if (!xalanContextNode) {
1016
- xalanContextNode = docWrapper;
1170
+ xalanContextNode = ctx->docWrapper;
1017
1171
  }
1018
1172
 
1019
- // Set up XPath factories and contexts
1020
- XPathEnvSupportDefault envSupport;
1021
- XObjectFactoryDefault objectFactory;
1022
- XPathExecutionContextDefault executionContext(envSupport, domSupport, objectFactory);
1023
- XPathConstructionContextDefault constructionContext;
1024
- XPathFactoryDefault factory;
1173
+ // Get or compile XPath expression (cached)
1174
+ XPath* xpath = get_or_compile_xpath(doc_wrapper, ctx, xpath_str);
1025
1175
 
1026
- // Create XPath
1027
- XPathProcessorImpl processor;
1028
- XPath* xpath = factory.create();
1176
+ // Create resolver for execution
1177
+ XalanElement* docElem = ctx->docWrapper->getDocumentElement();
1178
+ ElementPrefixResolverProxy resolver(docElem, *ctx->envSupport, *ctx->domSupport);
1029
1179
 
1030
- // Compile XPath expression
1031
- ElementPrefixResolverProxy resolver(docWrapper->getDocumentElement(), envSupport, domSupport);
1032
- processor.initXPath(*xpath, constructionContext, XalanDOMString(xpath_str), resolver);
1180
+ // Reset execution context for clean state
1181
+ ctx->objectFactory->reset();
1033
1182
 
1034
1183
  // Execute XPath query
1035
- const XObjectPtr result = xpath->execute(xalanContextNode, resolver, executionContext);
1184
+ const XObjectPtr result = xpath->execute(xalanContextNode, resolver, *ctx->executionContext);
1036
1185
 
1037
1186
  VALUE nodes_array = rb_ary_new();
1038
1187
 
@@ -1045,7 +1194,7 @@ static VALUE execute_xpath_with_xalan(DOMNode* context_node, const char* xpath_s
1045
1194
  XalanNode* xalanNode = nodeList.item(i);
1046
1195
  if (xalanNode) {
1047
1196
  // Map back to Xerces DOM node
1048
- const DOMNode* domNode = docWrapper->mapNode(xalanNode);
1197
+ const DOMNode* domNode = ctx->docWrapper->mapNode(xalanNode);
1049
1198
  if (domNode) {
1050
1199
  rb_ary_push(nodes_array, wrap_node(const_cast<DOMNode*>(domNode), doc_ref));
1051
1200
  }
@@ -1053,7 +1202,7 @@ static VALUE execute_xpath_with_xalan(DOMNode* context_node, const char* xpath_s
1053
1202
  }
1054
1203
  }
1055
1204
 
1056
- factory.returnObject(xpath);
1205
+ // Don't return xpath to factory - it's cached!
1057
1206
 
1058
1207
  NodeSetWrapper* wrapper = ALLOC(NodeSetWrapper);
1059
1208
  wrapper->nodes_array = nodes_array;
@@ -1073,6 +1222,118 @@ static VALUE execute_xpath_with_xalan(DOMNode* context_node, const char* xpath_s
1073
1222
  wrapper->nodes_array = rb_ary_new();
1074
1223
  return TypedData_Wrap_Struct(rb_cNodeSet, &nodeset_type, wrapper);
1075
1224
  }
1225
+
1226
+ // Optimized version that only returns the first matching node (for at_xpath)
1227
+ // Avoids creating Ruby wrappers for all nodes when we only need one
1228
+ static VALUE execute_xpath_with_xalan_first(DOMNode* context_node, const char* xpath_str, VALUE doc_ref) {
1229
+ // Validate XPath expression before execution
1230
+ validate_xpath_expression(xpath_str);
1231
+
1232
+ ensure_xerces_initialized();
1233
+
1234
+ try {
1235
+ // Get the document wrapper
1236
+ DocumentWrapper* doc_wrapper;
1237
+ TypedData_Get_Struct(doc_ref, DocumentWrapper, &document_type, doc_wrapper);
1238
+
1239
+ DOMDocument* domDoc = doc_wrapper->doc;
1240
+ if (!domDoc) {
1241
+ return Qnil;
1242
+ }
1243
+
1244
+ // Get or create cached Xalan context
1245
+ XalanContext* ctx = get_or_create_xalan_context(doc_wrapper);
1246
+ if (!ctx) {
1247
+ rb_raise(rb_eRuntimeError, "Failed to create Xalan context");
1248
+ }
1249
+
1250
+ // Map the context node to Xalan
1251
+ XalanNode* xalanContextNode = ctx->docWrapper->mapNode(context_node);
1252
+ if (!xalanContextNode) {
1253
+ xalanContextNode = ctx->docWrapper;
1254
+ }
1255
+
1256
+ // Get or compile XPath expression (cached)
1257
+ XPath* xpath = get_or_compile_xpath(doc_wrapper, ctx, xpath_str);
1258
+
1259
+ // Create resolver for execution
1260
+ XalanElement* docElem = ctx->docWrapper->getDocumentElement();
1261
+ ElementPrefixResolverProxy resolver(docElem, *ctx->envSupport, *ctx->domSupport);
1262
+
1263
+ // Reset execution context for clean state
1264
+ ctx->objectFactory->reset();
1265
+
1266
+ // Execute XPath query
1267
+ const XObjectPtr result = xpath->execute(xalanContextNode, resolver, *ctx->executionContext);
1268
+
1269
+ if (result.get() != 0) {
1270
+ // Check if result is a node set
1271
+ const NodeRefListBase& nodeList = result->nodeset();
1272
+ if (nodeList.getLength() > 0) {
1273
+ XalanNode* xalanNode = nodeList.item(0);
1274
+ if (xalanNode) {
1275
+ // Map back to Xerces DOM node - only wrap the first one!
1276
+ const DOMNode* domNode = ctx->docWrapper->mapNode(xalanNode);
1277
+ if (domNode) {
1278
+ return wrap_node(const_cast<DOMNode*>(domNode), doc_ref);
1279
+ }
1280
+ }
1281
+ }
1282
+ }
1283
+
1284
+ return Qnil;
1285
+
1286
+ } catch (const XalanXPathException& e) {
1287
+ CharStr msg(e.getMessage().c_str());
1288
+ rb_raise(rb_eRuntimeError, "XPath error: %s", msg.localForm());
1289
+ } catch (const XMLException& e) {
1290
+ CharStr message(e.getMessage());
1291
+ rb_raise(rb_eRuntimeError, "XML error: %s", message.localForm());
1292
+ } catch (...) {
1293
+ rb_raise(rb_eRuntimeError, "Unknown XPath error");
1294
+ }
1295
+
1296
+ return Qnil;
1297
+ }
1298
+ #endif
1299
+
1300
+ #ifndef HAVE_XALAN
1301
+ // Keep the snapshot result semantics of xpath(), but allocate only one Ruby
1302
+ // node for first-match queries. Xerces' XPath subset need not support every
1303
+ // result type exposed by the DOM XPath API.
1304
+ static VALUE execute_xpath_with_xerces_first(DOMNode* context_node, const char* xpath_str, VALUE doc_ref) {
1305
+ if (!context_node) return Qnil;
1306
+
1307
+ DocumentWrapper* wrapper;
1308
+ TypedData_Get_Struct(doc_ref, DocumentWrapper, &document_type, wrapper);
1309
+ try {
1310
+ std::unique_ptr<DOMXPathNSResolver, DOMRelease> resolver(
1311
+ wrapper->doc->createNSResolver(context_node));
1312
+ XStr path(xpath_str);
1313
+ std::unique_ptr<DOMXPathExpression, DOMRelease> expression(
1314
+ wrapper->doc->createExpression(path.unicodeForm(), resolver.get()));
1315
+ std::unique_ptr<DOMXPathResult, DOMRelease> result(expression->evaluate(
1316
+ context_node, DOMXPathResult::ORDERED_NODE_SNAPSHOT_TYPE, NULL));
1317
+
1318
+ DOMNode* node = nullptr;
1319
+ if (result->getSnapshotLength() > 0 && result->snapshotItem(0)) {
1320
+ node = result->getNodeValue();
1321
+ }
1322
+ result.reset();
1323
+ expression.reset();
1324
+ resolver.reset();
1325
+ return wrap_node(node, doc_ref);
1326
+ } catch (const DOMXPathException& e) {
1327
+ CharStr message(e.getMessage());
1328
+ rb_raise(rb_eRuntimeError, "XPath error: %s", message.localForm());
1329
+ } catch (const DOMException& e) {
1330
+ CharStr message(e.getMessage());
1331
+ rb_raise(rb_eRuntimeError, "DOM error: %s", message.localForm());
1332
+ } catch (...) {
1333
+ rb_raise(rb_eRuntimeError, "Unknown XPath error");
1334
+ }
1335
+ return Qnil;
1336
+ }
1076
1337
  #endif
1077
1338
 
1078
1339
  // document.xpath(path)
@@ -1089,8 +1350,9 @@ static VALUE document_xpath(VALUE self, VALUE path) {
1089
1350
  Check_Type(path, T_STRING);
1090
1351
  const char* xpath_str = StringValueCStr(path);
1091
1352
 
1092
- // Validate XPath expression before execution
1353
+ #ifndef HAVE_XALAN
1093
1354
  validate_xpath_expression(xpath_str);
1355
+ #endif
1094
1356
 
1095
1357
  #ifdef HAVE_XALAN
1096
1358
  // Use Xalan for full XPath 1.0 support
@@ -1158,15 +1420,30 @@ static VALUE document_xpath(VALUE self, VALUE path) {
1158
1420
 
1159
1421
  // document.at_xpath(path) - returns first matching node or nil
1160
1422
  static VALUE document_at_xpath(VALUE self, VALUE path) {
1161
- VALUE nodeset = document_xpath(self, path);
1162
- NodeSetWrapper* wrapper;
1163
- TypedData_Get_Struct(nodeset, NodeSetWrapper, &nodeset_type, wrapper);
1423
+ DocumentWrapper* doc_wrapper;
1424
+ TypedData_Get_Struct(self, DocumentWrapper, &document_type, doc_wrapper);
1164
1425
 
1165
- if (RARRAY_LEN(wrapper->nodes_array) == 0) {
1426
+ if (!doc_wrapper->doc) {
1166
1427
  return Qnil;
1167
1428
  }
1168
1429
 
1169
- return rb_ary_entry(wrapper->nodes_array, 0);
1430
+ Check_Type(path, T_STRING);
1431
+ const char* xpath_str = StringValueCStr(path);
1432
+
1433
+ #ifndef HAVE_XALAN
1434
+ validate_xpath_expression(xpath_str);
1435
+ #endif
1436
+
1437
+ #ifdef HAVE_XALAN
1438
+ // Use optimized first-only version
1439
+ DOMElement* root = doc_wrapper->doc->getDocumentElement();
1440
+ if (!root) {
1441
+ return Qnil;
1442
+ }
1443
+ return execute_xpath_with_xalan_first(root, xpath_str, self);
1444
+ #else
1445
+ return execute_xpath_with_xerces_first(doc_wrapper->doc->getDocumentElement(), xpath_str, self);
1446
+ #endif
1170
1447
  }
1171
1448
 
1172
1449
  // document.css(selector) - Convert CSS to XPath and execute
@@ -1183,16 +1460,29 @@ static VALUE document_css(VALUE self, VALUE selector) {
1183
1460
 
1184
1461
  // document.at_css(selector) - Returns first matching node
1185
1462
  static VALUE document_at_css(VALUE self, VALUE selector) {
1186
- VALUE nodeset = document_css(self, selector);
1463
+ Check_Type(selector, T_STRING);
1464
+ const char* css_str = StringValueCStr(selector);
1187
1465
 
1188
- NodeSetWrapper* wrapper;
1189
- TypedData_Get_Struct(nodeset, NodeSetWrapper, &nodeset_type, wrapper);
1466
+ // Convert CSS to XPath
1467
+ std::string xpath_str = css_to_xpath(css_str);
1190
1468
 
1191
- if (RARRAY_LEN(wrapper->nodes_array) == 0) {
1469
+ #ifdef HAVE_XALAN
1470
+ DocumentWrapper* doc_wrapper;
1471
+ TypedData_Get_Struct(self, DocumentWrapper, &document_type, doc_wrapper);
1472
+
1473
+ if (!doc_wrapper->doc) {
1192
1474
  return Qnil;
1193
1475
  }
1194
1476
 
1195
- return rb_ary_entry(wrapper->nodes_array, 0);
1477
+ // Use optimized first-only version
1478
+ DOMElement* root = doc_wrapper->doc->getDocumentElement();
1479
+ if (!root) {
1480
+ return Qnil;
1481
+ }
1482
+ return execute_xpath_with_xalan_first(root, xpath_str.c_str(), self);
1483
+ #else
1484
+ return document_at_xpath(self, rb_str_new_cstr(xpath_str.c_str()));
1485
+ #endif
1196
1486
  }
1197
1487
 
1198
1488
  // node.inspect - human-readable representation
@@ -1447,10 +1737,8 @@ static VALUE node_children(VALUE self) {
1447
1737
  NodeWrapper* wrapper;
1448
1738
  TypedData_Get_Struct(self, NodeWrapper, &node_type, wrapper);
1449
1739
 
1450
- VALUE children = rb_ary_new();
1451
-
1452
1740
  if (!wrapper->node) {
1453
- return children;
1741
+ return rb_ary_new();
1454
1742
  }
1455
1743
 
1456
1744
  VALUE doc_ref = wrapper->doc_ref;
@@ -1458,8 +1746,10 @@ static VALUE node_children(VALUE self) {
1458
1746
  DOMNodeList* child_nodes = wrapper->node->getChildNodes();
1459
1747
  XMLSize_t count = child_nodes->getLength();
1460
1748
 
1461
- for (XMLSize_t i = 0; i < count; i++) {
1462
- DOMNode* child = child_nodes->item(i);
1749
+ // Pre-size array for better performance
1750
+ VALUE children = rb_ary_new_capa((long)count);
1751
+
1752
+ for (DOMNode* child = wrapper->node->getFirstChild(); child; child = child->getNextSibling()) {
1463
1753
  rb_ary_push(children, wrap_node(child, doc_ref));
1464
1754
  }
1465
1755
 
@@ -1471,18 +1761,18 @@ static VALUE node_element_children(VALUE self) {
1471
1761
  NodeWrapper* wrapper;
1472
1762
  TypedData_Get_Struct(self, NodeWrapper, &node_type, wrapper);
1473
1763
 
1474
- VALUE children = rb_ary_new();
1475
-
1476
1764
  if (!wrapper->node) {
1477
- return children;
1765
+ return rb_ary_new();
1478
1766
  }
1479
1767
 
1480
1768
  VALUE doc_ref = wrapper->doc_ref;
1481
1769
  DOMNodeList* child_nodes = wrapper->node->getChildNodes();
1482
1770
  XMLSize_t count = child_nodes->getLength();
1483
1771
 
1484
- for (XMLSize_t i = 0; i < count; i++) {
1485
- DOMNode* child = child_nodes->item(i);
1772
+ // Pre-size array (may be smaller than count, but good estimate)
1773
+ VALUE children = rb_ary_new_capa((long)count);
1774
+
1775
+ for (DOMNode* child = wrapper->node->getFirstChild(); child; child = child->getNextSibling()) {
1486
1776
  if (child->getNodeType() == DOMNode::ELEMENT_NODE) {
1487
1777
  rb_ary_push(children, wrap_node(child, doc_ref));
1488
1778
  }
@@ -1500,18 +1790,7 @@ static VALUE node_first_element_child(VALUE self) {
1500
1790
  return Qnil;
1501
1791
  }
1502
1792
 
1503
- VALUE doc_ref = wrapper->doc_ref;
1504
- DOMNodeList* child_nodes = wrapper->node->getChildNodes();
1505
- XMLSize_t count = child_nodes->getLength();
1506
-
1507
- for (XMLSize_t i = 0; i < count; i++) {
1508
- DOMNode* child = child_nodes->item(i);
1509
- if (child->getNodeType() == DOMNode::ELEMENT_NODE) {
1510
- return wrap_node(child, doc_ref);
1511
- }
1512
- }
1513
-
1514
- return Qnil;
1793
+ return element_child(wrapper->node, wrapper->doc_ref, false);
1515
1794
  }
1516
1795
 
1517
1796
  // node.last_element_child - returns last element child
@@ -1523,19 +1802,7 @@ static VALUE node_last_element_child(VALUE self) {
1523
1802
  return Qnil;
1524
1803
  }
1525
1804
 
1526
- VALUE doc_ref = wrapper->doc_ref;
1527
- DOMNodeList* child_nodes = wrapper->node->getChildNodes();
1528
- XMLSize_t count = child_nodes->getLength();
1529
-
1530
- // Search backwards for last element
1531
- for (XMLSize_t i = count; i > 0; i--) {
1532
- DOMNode* child = child_nodes->item(i - 1);
1533
- if (child->getNodeType() == DOMNode::ELEMENT_NODE) {
1534
- return wrap_node(child, doc_ref);
1535
- }
1536
- }
1537
-
1538
- return Qnil;
1805
+ return element_child(wrapper->node, wrapper->doc_ref, true);
1539
1806
  }
1540
1807
 
1541
1808
  // node.document - returns the document that owns this node
@@ -1918,11 +2185,7 @@ static VALUE node_inner_html(VALUE self) {
1918
2185
 
1919
2186
  // Build a string by serializing each child
1920
2187
  std::string result;
1921
- DOMNodeList* children = wrapper->node->getChildNodes();
1922
- XMLSize_t count = children->getLength();
1923
-
1924
- for (XMLSize_t i = 0; i < count; i++) {
1925
- DOMNode* child = children->item(i);
2188
+ for (DOMNode* child = wrapper->node->getFirstChild(); child; child = child->getNextSibling()) {
1926
2189
  XMLCh* xml_str = serializer->writeToString(child);
1927
2190
  CharStr utf8_str(xml_str);
1928
2191
  result += utf8_str.localForm();
@@ -2026,16 +2289,8 @@ static VALUE node_blank_p(VALUE self) {
2026
2289
 
2027
2290
  // Element nodes are blank if they have no child elements and no non-blank text
2028
2291
  if (wrapper->node->getNodeType() == DOMNode::ELEMENT_NODE) {
2029
- DOMNodeList* children = wrapper->node->getChildNodes();
2030
- XMLSize_t count = children->getLength();
2031
-
2032
- if (count == 0) {
2033
- return Qtrue;
2034
- }
2035
-
2036
- // Check if all children are blank text nodes
2037
- for (XMLSize_t i = 0; i < count; i++) {
2038
- DOMNode* child = children->item(i);
2292
+ // Check if all children are blank text nodes.
2293
+ for (DOMNode* child = wrapper->node->getFirstChild(); child; child = child->getNextSibling()) {
2039
2294
 
2040
2295
  // If there's an element child, not blank
2041
2296
  if (child->getNodeType() == DOMNode::ELEMENT_NODE) {
@@ -2080,8 +2335,9 @@ static VALUE node_xpath(VALUE self, VALUE path) {
2080
2335
  const char* xpath_str = StringValueCStr(path);
2081
2336
  VALUE doc_ref = node_wrapper->doc_ref;
2082
2337
 
2083
- // Validate XPath expression before execution
2338
+ #ifndef HAVE_XALAN
2084
2339
  validate_xpath_expression(xpath_str);
2340
+ #endif
2085
2341
 
2086
2342
  #ifdef HAVE_XALAN
2087
2343
  // Use Xalan for full XPath 1.0 support
@@ -2143,28 +2399,52 @@ static VALUE node_xpath(VALUE self, VALUE path) {
2143
2399
 
2144
2400
  // node.at_xpath(path) - returns first matching node or nil
2145
2401
  static VALUE node_at_xpath(VALUE self, VALUE path) {
2146
- VALUE nodeset = node_xpath(self, path);
2147
- NodeSetWrapper* wrapper;
2148
- TypedData_Get_Struct(nodeset, NodeSetWrapper, &nodeset_type, wrapper);
2402
+ NodeWrapper* node_wrapper;
2403
+ TypedData_Get_Struct(self, NodeWrapper, &node_type, node_wrapper);
2149
2404
 
2150
- if (RARRAY_LEN(wrapper->nodes_array) == 0) {
2405
+ if (!node_wrapper->node) {
2151
2406
  return Qnil;
2152
2407
  }
2153
2408
 
2154
- return rb_ary_entry(wrapper->nodes_array, 0);
2409
+ Check_Type(path, T_STRING);
2410
+ const char* xpath_str = StringValueCStr(path);
2411
+ VALUE doc_ref = node_wrapper->doc_ref;
2412
+
2413
+ #ifndef HAVE_XALAN
2414
+ validate_xpath_expression(xpath_str);
2415
+ #endif
2416
+
2417
+ #ifdef HAVE_XALAN
2418
+ // Use optimized first-only version
2419
+ return execute_xpath_with_xalan_first(node_wrapper->node, xpath_str, doc_ref);
2420
+ #else
2421
+ return execute_xpath_with_xerces_first(node_wrapper->node, xpath_str, doc_ref);
2422
+ #endif
2155
2423
  }
2156
2424
 
2157
2425
  // node.at_css(selector) - returns first matching node or nil
2158
2426
  static VALUE node_at_css(VALUE self, VALUE selector) {
2159
- VALUE nodeset = node_css(self, selector);
2160
- NodeSetWrapper* wrapper;
2161
- TypedData_Get_Struct(nodeset, NodeSetWrapper, &nodeset_type, wrapper);
2427
+ Check_Type(selector, T_STRING);
2428
+ const char* css_str = StringValueCStr(selector);
2162
2429
 
2163
- if (RARRAY_LEN(wrapper->nodes_array) == 0) {
2430
+ // Convert CSS to XPath
2431
+ std::string xpath_str = css_to_xpath(css_str);
2432
+
2433
+ #ifdef HAVE_XALAN
2434
+ NodeWrapper* node_wrapper;
2435
+ TypedData_Get_Struct(self, NodeWrapper, &node_type, node_wrapper);
2436
+
2437
+ if (!node_wrapper->node) {
2164
2438
  return Qnil;
2165
2439
  }
2166
2440
 
2167
- return rb_ary_entry(wrapper->nodes_array, 0);
2441
+ VALUE doc_ref = node_wrapper->doc_ref;
2442
+
2443
+ // Use optimized first-only version
2444
+ return execute_xpath_with_xalan_first(node_wrapper->node, xpath_str.c_str(), doc_ref);
2445
+ #else
2446
+ return node_at_xpath(self, rb_str_new_cstr(xpath_str.c_str()));
2447
+ #endif
2168
2448
  }
2169
2449
 
2170
2450
  // Helper function to convert basic CSS selectors to XPath
@@ -1,3 +1,3 @@
1
1
  module RXerces
2
- VERSION = "0.7.0".freeze
2
+ VERSION = "0.7.1".freeze
3
3
  end
@@ -0,0 +1 @@
1
+ 4d38e048acd6037386109d5b671c47322a28295b8f03d4f61143a3988ae9ce26 rxerces-0.7.1-unsigned.gem
data/rxerces.gemspec CHANGED
@@ -1,6 +1,6 @@
1
1
  Gem::Specification.new do |spec|
2
2
  spec.name = "rxerces"
3
- spec.version = "0.7.0"
3
+ spec.version = "0.7.1"
4
4
  spec.author = "Daniel J. Berger"
5
5
  spec.email = "djberg96@gmail.com"
6
6
  spec.cert_chain = ["certs/djberg96_pub.pem"]
@@ -0,0 +1,91 @@
1
+ require 'spec_helper'
2
+
3
+ RSpec.describe 'Native binding operations' do
4
+ it 'preserves child order and node types while walking siblings' do
5
+ doc = RXerces.XML('<root>text<!--before--><first/><![CDATA[data]]><last/><!--after--> </root>')
6
+ root = doc.root
7
+
8
+ expect(root.children.map(&:name)).to eq(
9
+ ['#text', '#comment', 'first', '#cdata-section', 'last', '#comment', '#text']
10
+ )
11
+ expect(root.element_children.map(&:name)).to eq(['first', 'last'])
12
+ expect(root.first_element_child.name).to eq('first')
13
+ expect(root.last_element_child.name).to eq('last')
14
+ end
15
+
16
+ it 'skips document comments and processing instructions for element access' do
17
+ doc = RXerces.XML('<!--before--><?test value?><root/><!--after-->')
18
+
19
+ expect(doc.children.map(&:name)).to eq(['#comment', 'test', 'root', '#comment'])
20
+ expect(doc.element_children.map(&:name)).to eq(['root'])
21
+ expect(doc.first_element_child.name).to eq('root')
22
+ expect(doc.last_element_child.name).to eq('root')
23
+ end
24
+
25
+ it 'returns nil for element endpoints when there are no element children' do
26
+ ['<root/>', '<root>text<!--comment--><![CDATA[data]]></root>'].each do |xml|
27
+ root = RXerces.XML(xml).root
28
+ expect(root.first_element_child).to be_nil
29
+ expect(root.last_element_child).to be_nil
30
+ expect(root.element_children).to be_empty
31
+ end
32
+ end
33
+
34
+ it 'reflects mutations in child traversal' do
35
+ root = RXerces.XML('<root><first/><last/></root>').root
36
+ root.first_element_child.remove
37
+ expect(root.first_element_child.name).to eq('last')
38
+ root.last_element_child.remove
39
+ expect(root.children).to be_empty
40
+ expect(root.first_element_child).to be_nil
41
+ expect(root.last_element_child).to be_nil
42
+ end
43
+
44
+ it 'returns the first XPath match in document order and respects node context' do
45
+ doc = RXerces.XML('<root><group><item id="1"/><item id="2"/></group><group><item id="3"/></group></root>')
46
+
47
+ expect(doc.at_xpath('//item')['id']).to eq('1')
48
+ expect(doc.root.last_element_child.at_xpath('.//item')['id']).to eq('3')
49
+ expect(doc.at_css('item')['id']).to eq('1')
50
+ expect(doc.root.at_css('item')['id']).to eq('1')
51
+ expect(doc.at_xpath('//missing')).to be_nil
52
+ expect(doc.root.at_xpath('.//missing')).to be_nil
53
+ expect(doc.at_css('missing')).to be_nil
54
+ expect(doc.root.at_css('missing')).to be_nil
55
+ end
56
+
57
+ it 'validates first-match XPath expressions' do
58
+ doc = RXerces.XML('<root/>')
59
+ [doc, doc.root].each do |context|
60
+ expect { context.at_xpath('') }.to raise_error(ArgumentError)
61
+ expect { context.at_xpath('document("file.xml")') }.to raise_error(ArgumentError)
62
+ expect { context.at_xpath('[') }.to raise_error(ArgumentError)
63
+ end
64
+ end
65
+
66
+ it 'keeps the document alive through first-match results' do
67
+ node = RXerces.XML('<root><item id="1"/></root>').at_xpath('//item')
68
+ GC.start
69
+ expect(node['id']).to eq('1')
70
+ expect(node.document.root.name).to eq('root')
71
+ end
72
+
73
+ it 'serializes UTF-8 with a matching declaration and round-trips Unicode' do
74
+ text = 'café 日本語 😀 & < >'
75
+ doc = RXerces.XML('<root>café 日本語 😀 &amp; &lt; &gt;</root>')
76
+ serialized = doc.to_xml
77
+
78
+ expect(serialized.encoding).to eq(Encoding::UTF_8)
79
+ expect(serialized).to be_valid_encoding
80
+ expect(serialized).to include('encoding="UTF-8"')
81
+ expect(RXerces.XML(serialized).root.text.b).to eq(text.b)
82
+ end
83
+
84
+ it 'serializes non-UTF-8 input as correctly declared UTF-8' do
85
+ doc = RXerces.XML('<?xml version="1.0" encoding="ISO-8859-1"?><root>caf&#233;</root>')
86
+ serialized = doc.to_xml
87
+
88
+ expect(serialized).to include('encoding="UTF-8"', 'café')
89
+ expect(RXerces.XML(serialized).root.text.b).to eq('café'.b)
90
+ end
91
+ end
@@ -4,7 +4,7 @@ require 'rxerces'
4
4
 
5
5
  RSpec.shared_examples RXerces do
6
6
  example 'version number is set to the expected value' do
7
- expect(RXerces::VERSION).to eq('0.7.0')
7
+ expect(RXerces::VERSION).to eq('0.7.1')
8
8
  expect(RXerces::VERSION).to be_frozen
9
9
  end
10
10
  end
data.tar.gz.sig CHANGED
@@ -1 +1,3 @@
1
- 7�i}��S���WaX�%4i&zq��:|.��c
1
+ .�60$˔AHN��^��+�s6�*X�9D[H�hؾ�Xh|Wy�n�(��D8���ŒBQWؖ��ͤ���3� ^�Y���t�ja�H-U��I��S�l�B� ������0�.���AK�A����l�m�>�\ t��A��
2
+ L� K���DzxK�������C'���65Oh�J�L�ɇ_p�}��\���A�\�E�uOŏ�0��i�a���MCs��_!�z�$�=gYK�U3�n�,�����=l4���h�@�������?�Q6�}v�4�&���ֵR���@�|4{p�&�Lvm�,�3*q�
3
+ d
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: rxerces
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.7.0
4
+ version: 0.7.1
5
5
  platform: ruby
6
6
  authors:
7
7
  - Daniel J. Berger
@@ -107,6 +107,7 @@ files:
107
107
  - README.md
108
108
  - Rakefile
109
109
  - benchmarks/README.md
110
+ - benchmarks/bindings_benchmark.rb
110
111
  - benchmarks/css_benchmark.rb
111
112
  - benchmarks/parse_benchmark.rb
112
113
  - benchmarks/run_all.rb
@@ -116,20 +117,19 @@ files:
116
117
  - benchmarks/xpath_validation_cache_benchmark.rb
117
118
  - benchmarks/xpath_validation_micro_benchmark.rb
118
119
  - certs/djberg96_pub.pem
119
- - e
120
120
  - examples/basic_usage.rb
121
121
  - examples/schema_example.rb
122
122
  - examples/simple_example.rb
123
123
  - examples/xpath_example.rb
124
124
  - ext/rxerces/extconf.rb
125
- - ext/rxerces/rxerces.bundle.dSYM/Contents/Info.plist
126
- - ext/rxerces/rxerces.bundle.dSYM/Contents/Resources/Relocations/aarch64/rxerces.bundle.yml
127
125
  - ext/rxerces/rxerces.cpp
128
126
  - ext/rxerces/rxerces.h
129
127
  - lib/rxerces.rb
130
128
  - lib/rxerces/nokogiri.rb
131
129
  - lib/rxerces/version.rb
130
+ - pkg/rxerces-0.7.1-unsigned.gem.sha256
132
131
  - rxerces.gemspec
132
+ - spec/bindings_spec.rb
133
133
  - spec/document_spec.rb
134
134
  - spec/element_spec.rb
135
135
  - spec/node_spec.rb
@@ -141,8 +141,6 @@ files:
141
141
  - spec/spec_helper.rb
142
142
  - spec/xpath_cache_spec.rb
143
143
  - spec/xpath_spec.rb
144
- - tmp/arm64-darwin24/rxerces/3.4.8/rxerces.bundle.dSYM/Contents/Info.plist
145
- - tmp/arm64-darwin24/rxerces/3.4.8/rxerces.bundle.dSYM/Contents/Resources/Relocations/aarch64/rxerces.bundle.yml
146
144
  homepage: http://github.com/djberg96/rxerces
147
145
  licenses:
148
146
  - MIT
@@ -170,10 +168,11 @@ required_rubygems_version: !ruby/object:Gem::Requirement
170
168
  - !ruby/object:Gem::Version
171
169
  version: '0'
172
170
  requirements: []
173
- rubygems_version: 3.6.9
171
+ rubygems_version: 4.0.20
174
172
  specification_version: 4
175
173
  summary: Nokogiri-compatible XML library using Xerces-C
176
174
  test_files:
175
+ - spec/bindings_spec.rb
177
176
  - spec/document_spec.rb
178
177
  - spec/element_spec.rb
179
178
  - spec/node_spec.rb
metadata.gz.sig CHANGED
Binary file
data/e DELETED
File without changes
@@ -1,20 +0,0 @@
1
- <?xml version="1.0" encoding="UTF-8"?>
2
- <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3
- <plist version="1.0">
4
- <dict>
5
- <key>CFBundleDevelopmentRegion</key>
6
- <string>English</string>
7
- <key>CFBundleIdentifier</key>
8
- <string>com.apple.xcode.dsym.rxerces.bundle</string>
9
- <key>CFBundleInfoDictionaryVersion</key>
10
- <string>6.0</string>
11
- <key>CFBundlePackageType</key>
12
- <string>dSYM</string>
13
- <key>CFBundleSignature</key>
14
- <string>????</string>
15
- <key>CFBundleShortVersionString</key>
16
- <string>1.0</string>
17
- <key>CFBundleVersion</key>
18
- <string>1</string>
19
- </dict>
20
- </plist>
@@ -1,5 +0,0 @@
1
- ---
2
- triple: 'arm64-apple-darwin'
3
- binary-path: rxerces.bundle
4
- relocations: []
5
- ...
@@ -1,20 +0,0 @@
1
- <?xml version="1.0" encoding="UTF-8"?>
2
- <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3
- <plist version="1.0">
4
- <dict>
5
- <key>CFBundleDevelopmentRegion</key>
6
- <string>English</string>
7
- <key>CFBundleIdentifier</key>
8
- <string>com.apple.xcode.dsym.rxerces.bundle</string>
9
- <key>CFBundleInfoDictionaryVersion</key>
10
- <string>6.0</string>
11
- <key>CFBundlePackageType</key>
12
- <string>dSYM</string>
13
- <key>CFBundleSignature</key>
14
- <string>????</string>
15
- <key>CFBundleShortVersionString</key>
16
- <string>1.0</string>
17
- <key>CFBundleVersion</key>
18
- <string>1</string>
19
- </dict>
20
- </plist>
@@ -1,5 +0,0 @@
1
- ---
2
- triple: 'arm64-apple-darwin'
3
- binary-path: rxerces.bundle
4
- relocations: []
5
- ...