简体   繁体   中英

Error while parsing XML using Java

I am trying to parse A xml document which I have obtained from Google Geocode Api .

My XML File. I have a series of such data in the Same file. this is just one node

<?xml version="1.0" encoding="UTF-8"?> 
<GeocodeResponse>
<status>OK</status>
 <result>
  <formatted_address>Petroleum House, Jamshedji Tata Road, Churchgate, Mumbai, Maharashtra 400020, India</formatted_address>
  <address_component>
<long_name>Petroleum House</long_name>
<short_name>Petroleum House</short_name>
</address_component>
<address_component>
<long_name>Jamshedji Tata Road</long_name>
<short_name>Jamshedji Tata Road</short_name>
<type>route</type>
</address_component>
<address_component>
<long_name>Churchgate</long_name>
<short_name>Churchgate</short_name>
<type>sublocality</type>
<type>political</type>
</address_component>
<address_component>
<long_name>Mumbai</long_name>
<short_name>मॿंबई</short_name>
<type>locality</type>
<type>political</type>
</address_component>
<address_component>
<long_name>Mumbai</long_name>
<short_name>Mumbai</short_name>
<type>administrative_area_level_2</type>
<type>political</type>
</address_component>
<address_component>
<long_name>Maharashtra</long_name>
<short_name>MH</short_name>
<type>administrative_area_level_1</type>
<type>political</type>
</address_component>
<address_component>
<long_name>India</long_name>
<short_name>IN</short_name>
<type>country</type>
<type>political</type>
</address_component>
<address_component>
<long_name>400020</long_name>
<short_name>400020</short_name>
<type>postal_code</type>
</address_component>
<geometry>
<location>
<lat>18.9291061</lat>
<lng>72.8255146</lng>
</location>
<location_type>APPROXIMATE</location_type>
<viewport>
<southwest>
<lat>18.9277189</lat>
<lng>72.8240293</lng>
</southwest>
<northeast>
<lat>18.9304168</lat>
<lng>72.8267272</lng>
</northeast>
</viewport>
<bounds>
<southwest>
<lat>18.9288559</lat>
<lng>72.8251686</lng>
</southwest>
<northeast>
<lat>18.9292798</lat>
<lng>72.8255879</lng>
</northeast>
</bounds>
</geometry>
</result>
</GeocodeResponse>

I am trying to use the following code but I am getting some error.This is the first time me trying to parse an XML.

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class parser {

public static void main(String args[]) {
    try {

        File stocks = new File("filename.xml");
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory
                .newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(stocks);
        doc.getDocumentElement().normalize();

        System.out.println("root of xml file"
                + doc.getDocumentElement().getNodeName());
        NodeList nodes = doc.getElementsByTagName("address_component");
        System.out.println("==========================");

        for (int i = 0; i < nodes.getLength(); i++) {
            Node node = nodes.item(i);

            if (node.getNodeType() == Node.ELEMENT_NODE) {
                Element element = (Element) node;
                System.out.println("Name: "
                        + getValue("long_name", element));
                System.out.println("lat: " + getValue("lat", element));
                System.out.println("lon: " + getValue("lon", element));
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

private static String getValue(String tag, Element element) {
    NodeList nodes = element.getElementsByTagName(tag).item(0)
            .getChildNodes();
    Node node = (Node) nodes.item(0);
    return node.getNodeValue();
}

`` }

The error I am getting

com.sun.org.apache.xerces.internal.impl.io.MalformedByteSequenceException: Invalid byte 3 of 3-byte UTF-8 sequence.
at com.sun.org.apache.xerces.internal.impl.io.UTF8Reader.invalidByte(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.io.UTF8Reader.read(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLEntityScanner.load(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLEntityScanner.scanContent(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(Unknown Source)
at javax.xml.parsers.DocumentBuilder.parse(Unknown Source)
at parser.main(parser.java:17)

Direct Ouput from Google

<?xml version="1.0" encoding="UTF-8"?>
<GeocodeResponse>
<status>OK</status>
<result>
<formatted_address>Petroleum House, Jamshedji Tata Road, Churchgate, Mumbai, Maharashtra 400020, India</formatted_address>
<address_component>
<long_name>Petroleum House</long_name>
<short_name>Petroleum House</short_name>
</address_component>
<address_component>
<long_name>Jamshedji Tata Road</long_name>
<short_name>Jamshedji Tata Road</short_name>
<type>route</type>
</address_component>
<address_component>
<long_name>Churchgate</long_name>
<short_name>Churchgate</short_name>
<type>sublocality</type>
<type>political</type>
</address_component>
<address_component>
<long_name>Mumbai</long_name>
<short_name>म�ंबई</short_name>
<type>locality</type>
<type>political</type>
</address_component>
<address_component>
<long_name>Mumbai</long_name>
<short_name>Mumbai</short_name>
<type>administrative_area_level_2</type>
<type>political</type>
</address_component>
<address_component>
<long_name>Maharashtra</long_name>
<short_name>MH</short_name>
<type>administrative_area_level_1</type>
<type>political</type>
</address_component>
<address_component>
<long_name>India</long_name>
<short_name>IN</short_name>
<type>country</type>
<type>political</type>
</address_component>
<address_component>
<long_name>400020</long_name>
<short_name>400020</short_name>
<type>postal_code</type>
</address_component>
<geometry>
<location>
<lat>18.9291061</lat>
<lng>72.8255146</lng>
</location>
<location_type>APPROXIMATE</location_type>
<viewport>
<southwest>
<lat>18.9277189</lat>
<lng>72.8240293</lng>
</southwest>
<northeast>
<lat>18.9304168</lat>
<lng>72.8267272</lng>
</northeast>
</viewport>
<bounds>
<southwest>
<lat>18.9288559</lat>
<lng>72.8251686</lng>
</southwest>
<northeast>
<lat>18.9292798</lat>
<lng>72.8255879</lng>
</northeast>
</bounds>
</geometry>
</result>
</GeocodeResponse>

This is the direct output from google

I suspect the file has been misencoded whilst being saved.

Your file says UTF-8 at the top, but whatever has saved it hasn't saved it as UTF-8. You should be able to confirm this by viewing via another XML-capable tool eg a browser or perhaps a command-line tool such as XMLStarlet .

Can you get that input direct from the Google service ? ie don't save it as an intermediate file. That would be worth doing if only to confirm this issue.

I would say it has to do with the file encoding. If you are on a windows machine it could translate the xml file as the windows ISO format instead of UTF-8

I would try to replace the

Document doc = dBuilder.parse(stocks);

with:

Document doc = dBuilder.parse(new FileInputStream(stocks), "UTF8")));

To make sure the input file is read as UTF-8

Edit: How to check the files encoding with notepad++

Notepad ++编码检查

You can try to parse your file like this:

File file = new File("filename.xml");
InputStream inputStream= new FileInputStream(file);
Reader reader = new InputStreamReader(inputStream,"UTF-8");
InputSource is = new InputSource(reader);
is.setEncoding("UTF-8");
Document doc = dBuilder.parse(is);

That's just a wild guess tho...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM