我想解析一个 XML 字符串并将其显示在 EditText 中,但我不能,我不明白可能是什么问题,请帮忙,我的代码:
私有字符串 xmlc ="<game><cel>5</cel><val>2</val></game>";
private CharSequence readXML(String xmlc2) throws XmlPullParserException {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
XmlPullParser xpp = factory.newPullParser();
String results = "";
String celda = "";
String valor = "";
xpp.setInput(new StringReader (xmlc2));
int eventType = xpp.getEventType();
String tagName = xpp.getName();
try {
while (eventType != XmlPullParser.END_DOCUMENT) {
if(tagName.equalsIgnoreCase("cell")){
celda = xpp.nextText();
} else if(tagName.equalsIgnoreCase("val")){
valor = xpp.nextText();
}
xpp.nextTag();
}
} catch (Exception e) {
Toast.makeText(this, "error!", Toast.LENGTH_LONG).show();
}
return celda;
}
感谢您的建议,现在我可以将字符串 xml 作为参数发送并进行解析,但我不知道如何保存找到的 2 个值并在不同的 EditText 中显示每个值?
private EditText et02;
private EditText et03;
private String xmlc = "<game><cel>5</cel><val>2</val></game>";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText et02 = (EditText)findViewById(R.id.et02);
EditText et03 = (EditText)findViewById(R.id.et03);
TextView myXmlContent = (TextView)findViewById(R.id.xml_tv);
String stringXmlContent;
stringXmlContent = getAllXML();
myXmlContent.setText(stringXmlContent);
}
public String getAllXML(){
Activity activity = this;
String str = "";
//For file source
//Resources res = activity.getResources();
//XmlResourceParser xpp = res.getXml(R.xml.test);
try {
//For String source
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(new StringReader(xmlc));
xpp.next();
int eventType = xpp.getEventType();
while (xpp.getEventType()!=XmlPullParser.END_DOCUMENT) {
if (xpp.getEventType()==XmlPullParser.START_TAG) {
if (xpp.getName().equals("cel")) {
str += "\ncell : "+xpp.nextText();
}
if (xpp.getName().equals("val")) {
str += "\nval : "+xpp.nextText();
}
}
xpp.next();
}
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}