Android Studio(java)中JDOM2包的XML解析器出错

hts6caw3  于 2023-05-12  发布在  Android
关注(0)|答案(1)|浏览(134)

这段代码应该将xml转换为json,我在第一个错误中得到了下面的错误。SAXBuilder无法读取xml文件。
我在这个代码中使用了JDOM2库。
Java代码:

package com.example.books_xmltojson;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.EditText;
import org.jdom2.Document;
import org.jdom2.input.SAXBuilder;
import java.io.InputStream;

public class MainActivity extends AppCompatActivity {
    EditText edittext;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        edittext = findViewById(R.id.edittext);
        // SAX builder 
        InputStream input = getResources().openRawResource(R.raw.books);
        SAXBuilder builder = new SAXBuilder();
        try {
            Document doc = builder.build(input);
        } catch (Exception e) {
                edittext.setText(e.toString());
      } 
   }
}

XML R.raw.books:

// Resources
<catalog>
   <book>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>

   </book>
   <book>
      <title>Midnight Rain</title>
      <genre>Fantasy</genre>
   </book>
</catalog>

错误:
org.jdom2.JDOMException:http://xml.org/sax/features/external-general-entities功能http://xml.org/sax/features/external-general-entities不支持SAX驱动程序org.apache.harmony.xml.ExpatReader

wyyhbhjk

wyyhbhjk1#

首先,我必须在项目中实现xercesImpl.jar。然后我不得不改变SAXBuilder如下:

SAXBuilder builder = new SAXBuilder("org.apache.xerces.parsers.SAXParser");
builder.setFeature("http://xml.org/sax/features/external-general-entities", false);

而且你猜怎么着,ChatGPT一步一步地解决了我的问题。太棒了。

相关问题