非法角色'&'在原始字符串REXML解析中

时间:2013-06-21 14:05:57

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-3.2 rexml

我正在尝试使用REXML解析XML文件....当我的XML文件中存在非法字符时......此时它的jus失败了。

那么我们有什么方法可以替换或删除这些字符吗?

无法解析错误字符'&'在原始字符串REXML解析

<head> Negative test for underlying BJSPRICEENG N4&N5
</head>


doc = REXML::Document.new(File.open(file_name,"r:iso-8859-1:utf-8"))

testfile.elements["head"].text





doc = REXML::Document.new(content)
dir_path = doc.elements["TestBed/TestDir"].attributes["path"].to_s
    doc.elements.each("TestBed/TestDir") do |directory|
      directory.elements.each("file") do |testfile|

t= testfile.elements["head"].text

end
end
end




<file name="toptstocksensbybjs.m">
      <MCheck></MCheck>
      <TestExtension></TestExtension>
      <TestType></TestType>


<fcn name="lvlTwoDocExample" linenumber="20">
 <head> P1><&
</head>

 </fcn>

   </file>

1 个答案:

答案 0 :(得分:7)

对于您的情况,要删除非法的&字符,您可以尝试:

content = File.open(file_name,"r:iso-8859-1:utf-8").read
content.gsub!(/&(?!(?:amp|lt|gt|quot|apos);)/, '&amp;')
doc = REXML::Document.new(content)

但是,对于那些其他非法字符,尤其是那些未配对的<>'",这将更加困难。