我想在java中使用dom解析来解析下面的xml。
<?xml version="1.0" encoding="utf-8" ?>
<PFA date="201303312200" type="daily">
<Person id="90061" action="chg" date="31-Mar-2013">
<Gender>Male</Gender>
<ActiveStatus>Active</ActiveStatus>
<Deceased>No</Deceased>
<NameDetails>
<Name NameType="Primary Name">
<NameValue>
<TitleHonorific>Major General</TitleHonorific>
<FirstName>Aslan</FirstName>
<MiddleName>Ibraimis Dze</MiddleName>
<Surname>Abashidze</Surname>
<OriginalScriptName>مرحبا</OriginalScriptName>
</NameValue>
</Name>
</NameDetails>
</Person></PFA>
使用以下java代码解析此代码
public class ParseXml {
public static void main(String[] args) {
String file = "PFA2_201303312200_D.xml";
if (args.length > 0) {
file = args[0];
}
try{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new File(file));
System.out.println("Encoder Forment : " +document.getInputEncoding());
Element parentRoot = document.getDocumentElement();
System.out.println("Master Node is : "+parentRoot.getTagName());
for(int i =0;i<parentRoot.getChildNodes().getLength();i++){
Element root = (Element)parentRoot.getChildNodes().item(i);
该文件已经是一个utf-8文件,在从IDE(Eclipse)读取数据时,我将其他语言脚本的数据作为???????
。我该如何解决这个问题?
答案 0 :(得分:0)
问题与XML本身无关。 Java字符串是UTF-16编码的,Document
正在将XML数据从UTF-8正确解码为UTF-16字符串。真正的问题是您将Eclipse配置为使用不支持您尝试输出的字符的控制台字符集(阿拉伯语等),因此它们将替换为?
。尝试将控制台字符集设置为UTF-8,您应该看到正确的输出,因为UTF8&lt; - &gt; UTF16转换是无损的。
答案 1 :(得分:0)
转到此程序在eclipse中运行配置并转到Common选项卡,在其他选择按钮中将encoding设置为utf-8。