在scala中以UTF-8读取xml

时间:2022-10-24 22:34:38

I am trying to read a file to xml with the following code:

我正在尝试使用以下代码将文件读取到xml:

import scala.xml._

object HebrewToEnglishCityTranslator {

  val data = XML.loadFile("cities_hebrew_utf.xml");

  for(val entry <- data \\ "city") {
    val hebrewName = (entry \\ "hebrew_name").text
    val englishName = (entry \\ "english_name").text
    println(hebrewName + "=" + englishName)   }

However, my file is encoded in UTF-8 (hebrew chars) and XML encoding is val encoding = "ISO-8859-1"

但是,我的文件以UTF-8(希伯来语字符)编码,XML编码为val编码=“ISO-8859-1”

what should I do?

我该怎么办?

2 个解决方案

#1


13  

You should use XML.load(reader: java.io.Reader), which allows you to specify the file encoding:

您应该使用XML.load(reader:java.io.Reader),它允许您指定文件编码:


XML.load(new java.io.InputStreamReader(new java.io.FileInputStream("cities_hebrew_utf.xml"), "UTF-8")) 

#2


3  

Use the InputStream constructor instead of the String constructor. Good explanation of Stream vs. Reader xml reading here: Producing valid XML with Java and UTF-8 encoding

使用InputStream构造函数而不是String构造函数。这里有关于Stream与Reader xml的详细解释:使用Java和UTF-8编码生成有效的XML

#1


13  

You should use XML.load(reader: java.io.Reader), which allows you to specify the file encoding:

您应该使用XML.load(reader:java.io.Reader),它允许您指定文件编码:


XML.load(new java.io.InputStreamReader(new java.io.FileInputStream("cities_hebrew_utf.xml"), "UTF-8")) 

#2


3  

Use the InputStream constructor instead of the String constructor. Good explanation of Stream vs. Reader xml reading here: Producing valid XML with Java and UTF-8 encoding

使用InputStream构造函数而不是String构造函数。这里有关于Stream与Reader xml的详细解释:使用Java和UTF-8编码生成有效的XML