Class: VtdXml::Document

Inherits:
Object
  • Object
show all
Includes:
Navigation
Defined in:
lib/vtd_xml/document.rb

Constant Summary collapse

WITH_NAMESPACE_AWARE =
true

Instance Method Summary collapse

Methods included from Navigation

#clear_xpath_namespaces, #register_namespaces, #search, #xpath

Constructor Details

#initialize(contents) ⇒ Document

Returns a new instance of Document.



56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/vtd_xml/document.rb', line 56

def initialize(contents)
  @generator = VTDGen.new
  @generator.doc = contents.to_s.to_java_bytes
  @generator.parse(WITH_NAMESPACE_AWARE)

  @navigator = @generator.nav
  @pilot = AutoPilot.new(@navigator)
  @modifier = XMLModifier.new(@navigator)


rescue IllegalArgumentException, ParseException, EOFException => e
  raise ParseError, e.message
end

Instance Method Details

#add_child(xpath, xml, namespaces = {}) ⇒ Object



85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# File 'lib/vtd_xml/document.rb', line 85

def add_child(xpath, xml, namespaces = {})
  current_last_node = ''
  register_namespaces(namespaces)
  @pilot.select_xpath(xpath)
  found = @pilot.eval_xpath() != -1
  @modifier.insert_before_tail(xml) if found 
  found
rescue XPathParseException => e
  raise XPathError, e.message
rescue Java::ComXimpleware::ModifyException => e
  raise ModifyError, e.message
ensure
  @pilot.reset_xpath
  clear_xpath_namespaces
end

#insert_after(xpath, xml, namespaces = {}) ⇒ Object



70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/vtd_xml/document.rb', line 70

def insert_after(xpath, xml, namespaces = {})
  register_namespaces(namespaces)
  @pilot.select_xpath(xpath)
  found = @pilot.eval_xpath() != -1
  @modifier.insert_after_element(xml) if found
  found
rescue XPathParseException => e
  raise XPathError, e.message
rescue Java::ComXimpleware::ModifyException => e
  raise ModifyError, e.message
ensure
  @pilot.reset_xpath
  clear_xpath_namespaces
end

#select_node(xpath, namespaces = {}) ⇒ Object



101
102
103
104
105
106
107
108
109
110
111
112
# File 'lib/vtd_xml/document.rb', line 101

def select_node(xpath, namespaces={})
  register_namespaces(namespaces)
  @pilot.select_xpath(xpath)
  @navigator.to_raw_string(*offset_and_length_for(@navigator.element_fragment)) if @pilot.eval_xpath() != -1
rescue XPathParseException => e
  raise XPathError, e.message
rescue Java::ComXimpleware::ModifyException => e
  raise ModifyError, e.message
ensure
  @pilot.reset_xpath
  clear_xpath_namespaces
end

#to_xmlObject



114
115
116
117
118
# File 'lib/vtd_xml/document.rb', line 114

def to_xml
  os = ByteArrayOutputStream.new(@modifier.get_updated_document_size)
  @modifier.output(os)
  os.to_string('UTF-8')
end