我按照這個例子來解析xml example,但是當我嘗試解析xml時,出現錯誤。 該Xml是Reg Variacion =「20」/>用標籤解析xml
我需要顯示TextView []; 20,20,20
這是我的代碼:
MainActivity.java
public class MainActivity extends Activity {
SitesList sitesList = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/** Create a new layout to display the view */
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(1);
/** Create a new textview array to display the results */
TextView registro[];
TextView variacion[];
try {
/** Handling XML */
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
/** Send URL to parse XML Tags */
URL sourceUrl = new URL("http://www.bovalpo.com/cgi-local/xml_bcv.pl?URL=75");
/** Create handler to handle XML Tags (extends DefaultHandler) */
MyXMLHandler myXMLHandler = new MyXMLHandler();
xr.setContentHandler(myXMLHandler);
xr.parse(new InputSource(sourceUrl.openStream()));
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
/** Get result from MyXMLHandler SitlesList Object */
sitesList = MyXMLHandler.sitesList;
/** Assign textview array lenght by arraylist size */
registro = new TextView[sitesList.getRegistro().size()];
variacion = new TextView[sitesList.getVariacion().size()];
/** Set the result text in textview and add it to layout */
for (int i = 0; i < sitesList.getRegistro().size(); i++) {
registro[i] = new TextView(this);
registro[i].setText(sitesList.getRegistro().get(i));
variacion[i] = new TextView(this);
variacion[i].setText(sitesList.getVariacion().get(i));
layout.addView(registro[i]);
//layout.addView(category[i]);
}
/** Set the layout view to display */
setContentView(layout);
}
}
MyXMLHandler.java
DefaultHandler {
@Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
currentElement = true;
if (localName.equals("root"))
{
/** Start */
sitesList = new SitesList();
} else if (localName.equals("registro")) {
String attr = attributes.getValue("Variacion");
String var = String.valueOf(attr);
sitesList.setVariacion(var);
}
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
currentElement = false;
/** set value */
if (localName.equalsIgnoreCase("registro"))
sitesList.setRegistro(currentValue);
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if (currentElement) {
currentValue = new String(ch, start, length);
currentElement = false;
}
}
}
*「當我試圖解析XML,我得到錯誤」 *是相當模糊的,你能更具體? LogCat中的堆棧跟蹤是什麼意思?對於初學者,我可以告訴你'localName.equals(「registro」)'永遠不會是真的,因爲返回的xml顯示'Registro'(大寫'R')。 –
當你做某件事情並得到一個錯誤時,告訴我們錯誤是什麼。你可能不瞭解錯誤信息,但我們有很好的機會。 –
我解決了這個問題,解析錯誤 –