2011-11-09 74 views
0

我想分析其啓動一個GPX(XML)文檔如下:的Android解析XML錯誤 - 根元素名稱不匹配

<?xml version="1.0" encoding="UTF-8" standalone="no" ?> 
<gpx version="1.1" xmlns="http://www.topografix.com/GPX/1/1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd" creator="Ian"> 

當解析我得到follwoing錯誤:

android.sax.BadXmlException: Line 1: Root element name does not match. Expected: 'gpx', Got: 'http://www.topografix.com/GPX/1/1:gpx' 

但是,如果我然後刪除xmlns="http://www.topografix.com/GPX/1/1"屬性 - 它完美解析。

我使用解析的代碼是android.util.Xml.parse(is,Xml.Encoding.UTF_8,gpx.getContentHandler());

有誰知道爲什麼這個屬性cauing解析錯誤?

任何幫助非常感謝! Ian

回答

1

當您創建rootElement的,你有機會到指定命名空間...

final RootElement rootElement = new RootElement("http://www.topografix.com/GPX/1/1", "gpx");

0

這是不是有效的XML,我想你只是在最後缺少</gpx>,或者你可以在最後做/>自己關閉它。

+0

我不認爲這是OP的整個XML文檔;這只是第一個標籤。 (基於第一句中的「*開頭如下*」聲明。) –

+0

感謝您的關注,但我只是展示了xml文件的一部分。如果xmlns屬性不存在,它將在其他地方關閉並正確解析。 – Ian

0

您正在使用xmlns定義一個名稱空間(因此您的所有標記名稱將以您在此屬性中定義的任何內容開始),我猜測該模式無法識別。

0

我還沒有制定出如何解決問題,但如果其他人有相同的問題,您可以使用正則表達式從xml中刪除xmlns屬性。

private static InputStream stripDeclaration(InputStream is) throws UnsupportedEncodingException { 
    String string = new Scanner(is).useDelimiter("\\A").next(); 
    string = string.replaceFirst("xmlns=\".*?\"", ""); 
    return new ByteArrayInputStream(string.getBytes("UTF-8"));  
} 

,因爲你需要創建一個字符串出幾乎擊敗了SAX解析器的點你enitre XML文件。這是不理想的。任何更好的想法都非常受歡迎!