-1

I need to write a simple function to parsing xml from Url on java with DOM. This is xml url.

If i write this into /assets/exampleXML.xml and use this code all works.

static final String NODE_EMP = "Record";
static final String NODE_NAME = "Nominal";
static final String NODE_SALARY = "Value";
.....
public void onBtnClick3(View v) {
    XMLDOMParser parser = new XMLDOMParser();
    try {
        InputStream is = getAssets().open("exampleXML2.xml");
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(is);
        NodeList nodeList = doc.getElementsByTagName(NODE_EMP);
        for (int i = 0; i < nodeList.getLength(); i++) {
            Element e = (Element) nodeList.item(i);
            nameText.append(parser.getValue(e, NODE_NAME) + "\n");
            nameText.append(parser.getValue(e, NODE_SALARY) + "\n");
        }

But if i change to

public static final String QUERY_URL = "http://www.cbr.ru/scripts/XML_dynamic.asp?......";

public void onBtnClick(View v) {
    XMLDOMParser parser = new XMLDOMParser();
    try {
        URL url = new URL(QUERY_URL);
        URLConnection conn = url.openConnection();
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(conn.getInputStream());

This does not work. What is the problem and how to solve it? I have read it, but it does not work. Help me please. How to read XML response from a URL in java?

Community
  • 1
  • 1

1 Answers1

0

I don't really enjoy parsing XML by hand and I usually use POJOs and simple XML to do the work for me. Here is an example that uses Volley for the http communication and Simple XML

POJOs

@org.simpleframework.xml.Root(name="ValCurs", strict=false)
class ValCurs {

   @Attribute(name="ID") public String id;
   @Attribute(name="DateRange1") public String dateRange1;
   @Attribute(name="DateRange2") public String dateRange2;
   @Attribute public String name;

   @ElementList(inline = true)
   public List<Record> records;

   public ValCurs() {
      id = "";
      name = "";
      dateRange1 = "";
      dateRange2 = "";
      records = new ArrayList<Record>();

   }
}

@Root(name="Record")
class Record {
   @Attribute(name="Date") public String date;
   @Attribute(name="Id") public String id;
   @Element(name="Nominal") public String nominal;
   @Element(name="Value") public String value;

   public Record() {
      date = "";
      id = "";
      nominal = "";
      value = "";
   }
}

The UnitTest

@Test
    public void XMLTest() throws Exception {

        final CountDownLatch unitTestLatch = new CountDownLatch(1);
        String url = "http://www.cbr.ru/scripts/XML_dynamic.asp?VAL_NM_RQ=R01235&date_req1=01.08.2016&date_req2=18.08.2016&rt=1&mode=1[1]";

        Context appContext = InstrumentationRegistry.getTargetContext();
        RequestQueue queue = Volley.newRequestQueue(appContext);

        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
              new Response.Listener<String>() {
                  @Override
                  public void onResponse(String response) {

                      try {
                          Serializer serializer = new Persister();
                          ValCurs valcur = serializer.read(ValCurs.class, new StringReader(response), false);
                          Log.d("TAG", "Record size: " + valcur.records.size());

                      } catch (Exception e) {
                          e.printStackTrace();
                      }

                      unitTestLatch.countDown();
                  }
              }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                unitTestLatch.countDown();
            }
        });

        queue.add(stringRequest);

         unitTestLatch.await();
    }
Gary Bak
  • 4,746
  • 4
  • 22
  • 39