【问题标题】:Error while parsing XML using Java使用 Java 解析 XML 时出错
【发布时间】:2013-03-07 22:42:20
【问题描述】:

我正在尝试解析从 Google Geocode Api 获得的 xml 文档。

我的 XML 文件。我在同一个文件中有一系列这样的数据。这只是一个节点

<?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>

我正在尝试使用以下代码,但出现了一些错误。这是我第一次尝试解析 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();
}

``}

我遇到的错误

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)

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>

这是google的直接输出

【问题讨论】:

  • 好像File stocks = new File("filename.xml"); 没有加载文件
  • 该行加载文件。它只是声明了一个 File 对象。
  • 不错的收获@BrianAgnew
  • ... 那条线有效,因为他没有得到FileNotFoundException

标签: java xml parsing


【解决方案1】:

我会说这与文件编码有关。 如果您在 windows 机器上,它可以将 xml 文件转换为 windows ISO 格式而不是 UTF-8

我会尝试替换

Document doc = dBuilder.parse(stocks);

与:

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

确保输入文件被读取为 UTF-8

编辑: 如何用notepad++检查文件编码

【讨论】:

  • 正如 Brian Agnew 提到的,确保输入文件是真正的 UTF-8。
  • 我收到的数据直接来自谷歌服务,只是存储在一个文件中。
  • 如果你用文本编辑器(比如notepad++)打开文件,它说文件有什么样的编码? (npp-community.tuxfamily.org/documentation/notepad-user-manual/…)
  • 我只使用 NP++ 来查看数据,它正确显示
  • 那部分只说 XML 的编码而不是文件本身。略有不同。我编辑了我的原始帖子并添加了如何查看文件编码。
【解决方案2】:

您可以尝试像这样解析您的文件:

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);

这只是一个疯狂的猜测......

【讨论】:

  • 我尝试了您的代码..我收到以下错误 [致命错误] :80:2: 根元素之后的文档中的标记必须格式正确。 org.xml.sax.SAXParseException;行号:80;列号:2;文档中根元素之后的标记必须格式正确。在 com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(Unknown Source) 在 com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(Unknown Source) 在 parser.main(parser .java:27)
【解决方案3】:

我怀疑文件在保存时编码错误。

您的文件在顶部显示 UTF-8,但保存它的任何内容没有将其保存为 UTF-8。您应该能够通过另一个支持 XML 的工具查看来确认这一点,例如浏览器或命令行工具,例如XMLStarlet

您可以直接从 Google 服务获取输入吗?即不要将其保存为中间文件。如果只是为了确认这个问题,那将是值得的。

【讨论】:

  • 我已经添加了谷歌服务的直接输出
  • 请注意,如果您将输出 写入 到文件,则该写入必须支持 UTF-8。如果您将其加载到编辑器中然后将其写出,则 editor 必须保留编码。基本上,转换链中的所有内容都必须支持 UTF-8。我会使用 XMLStarlet 等独立工具在每个阶段检查是否没有发生损坏
猜你喜欢
  • 1970-01-01
  • 2012-06-01
  • 2016-06-12
  • 1970-01-01
  • 1970-01-01
  • 2015-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多