想知道是否可以使用REXML 3.1.7.3和ruby 1.9.3加载utf-16 xml文件。
以下是没有BOM的文件u16.xml中的xml数据:
<?xml version="1.0" encoding="utf-16"?>
<ArrayOfCatalogItem>
<CatalogItem>
<ID>bbe9b897-5d3b-4340-914b-fce8d6022bd9</ID>
<Name>EmployeeReport</Name>
</CatalogItem>
</ArrayOfCatalogItem>
使用以下代码加载它:
require "rexml/document"
file = File.new( "u16.xml" )
begin
doc = REXML::Document.new(file)
puts "doc = #{doc.to_s}"
rescue => err
puts "err = #{err.message}"
end
测试的输出:
err = #<REXML::ParseException: malformed XML: missing tag start
Line: 8
Position: 420
Last 80 unconsumed characters:
<?xml version="1.0" encoding="utf-16"?> <>
/Users/lucy/.rvm/rubies/ruby-1.9.3-p448/lib/ruby/1.9.1/rexml/parsers/baseparser.rb:367:in `pull_event'
/Users/lucy/.rvm/rubies/ruby-1.9.3-p448/lib/ruby/1.9.1/rexml/parsers/baseparser.rb:183:in `pull'
/Users/lucy/.rvm/rubies/ruby-1.9.3-p448/lib/ruby/1.9.1/rexml/parsers/treeparser.rb:22:in `parse'
/Users/lucy/.rvm/rubies/ruby-1.9.3-p448/lib/ruby/1.9.1/rexml/document.rb:245:in `build'
/Users/lucy/.rvm/rubies/ruby-1.9.3-p448/lib/ruby/1.9.1/rexml/document.rb:43:in `initialize'
xml-test.rb:6:in `new'
xml-test.rb:6:in `<main>'
...
malformed XML: missing tag start
Line: 8
Position: 420
Last 80 unconsumed characters:
<?xml version="1.0" encoding="utf-16"?> <
Line: 8
Position: 420
Last 80 unconsumed characters:
<?xml version="1.0" encoding="utf-16"?> <
如果我只是将xml文件更改为utf-8编码,则使用相同的代码成功加载:
doc = <?xml version='1.0' encoding='UTF-8'?>
<ArrayOfCatalogItem>
<CatalogItem>
<ID>bbe9b897-5d3b-4340-914b-fce8d6022bd9</ID>
<Name>EmployeeReport</Name>
</CatalogItem>
</ArrayOfCatalogItem>
那么可以用REXML加载utf-8 xml文件吗?在这种情况下,我必须使用REXML作为解析器。 任何建议将不胜感激。