- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个 XML 文件,如下所示:
<questions title="(Some question Category)">
<question>
<ask>(Some question)?</ask>
<answer>(Some answer)</answer>
<answer correct="true">(Some correct answer)</answer>
<answer>(Some answer)</answer>
<answer>(Some answer)</answer>
</question>
</questions>
我正在使用 SAX 来解析该文件。据我所知,所有必需的 SAX 文件都已正确设置。
然后我有一个处理程序类,我查找了如何为稍微不同的 XML 文件编写代码。我尝试针对上面的 xml 进行调整,这是我想到的(未完成):
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import android.content.Context;
import android.graphics.Color;
import android.util.Log;
import android.widget.TextView;
public class QuestionHandler extends DefaultHandler {
//list for imported product data
private ArrayList<TextView> theViews;
//string to track each entry
private String currQuestion = "";
//flags to keep track of XML processing
private boolean isAsk = false;
private boolean isAnswer = false;
//context for user interface
private Context theContext;
//constructor
public QuestionHandler(Context cont) {
super();
theViews = new ArrayList<TextView>();
theContext = cont;
}
//start of the XML document
public void startDocument () { Log.i("QuestionHandler", "Start of XML document"); }
//end of the XML document
public void endDocument () { Log.i("QuestionHandler", "End of XML document"); }
//opening element tag
public void startElement (String uri, String name, String qName, Attributes atts)
{
//find out if the element is a question
if(qName.equals("question"))
{
//set ask and answer tag to false
isAsk = false;
isAnswer = false;
//create View item for question display
TextView questionView = new TextView(theContext);
questionView.setTextColor(Color.rgb(73, 136, 83));
//add the attribute value to the displayed text
String viewText = "Items from " + atts.getValue("name") + ":";
questionView.setText(viewText);
//add the new view to the list
theViews.add(questionView);
}
//or if the element is an asked question
else if(qName.equals("ask"))
isAsk = true;
//or if element is an answer
else if(qName.equals("answer"))
isAnswer = true;
}
//closing element tag
public void endElement (String uri, String name, String qName)
{
if(qName.equals("question"))
{
//create a View item for the asked
TextView askView = new TextView(theContext);
askView.setTextColor(Color.rgb(192, 199, 95));
//display the compiled items
askView.setText(currQuestion);
//add to the list
theViews.add(askView);
//create a View item for the answers
TextView answersView = new TextView(theContext);
answersView.setTextColor(Color.rgb(192, 199, 95));
//display the compiled items
answersView.setText(currQuestion);
//add to the list
theViews.add(answersView);
//reset the variable for future items
currQuestion = "";
}
}
//element content
public void characters (char ch[], int start, int length)
{
//string to store the character content
String currText = "";
//loop through the character array
for (int i=start; i<start+length; i++)
{
switch (ch[i]) {
case '\\':
break;
case '"':
break;
case '\n':
break;
case '\r':
break;
case '\t':
break;
default:
currText += ch[i];
break;
}
}
//prepare for the next item
if(isAsk || isAnswer && currText.length()>0)
currQuestion += currText+"\n";
}
public ArrayList<TextView> getData()
{
//take care of SAX, input and parsing errors
try
{
//set the parsing driver
System.setProperty("org.xml.sax.driver","org.xmlpull.v1.sax2.Driver");
//create a parser
SAXParserFactory parseFactory = SAXParserFactory.newInstance();
SAXParser xmlParser = parseFactory.newSAXParser();
//get an XML reader
XMLReader xmlIn = xmlParser.getXMLReader();
//instruct the app to use this object as the handler
xmlIn.setContentHandler(this);
//provide the name and location of the XML file **ALTER THIS FOR YOUR FILE**
URL xmlURL = new URL("http://www.macs.hw.ac.uk/~pjbk/quiz/example.xml");
//open the connection and get an input stream
URLConnection xmlConn = xmlURL.openConnection();
InputStreamReader xmlStream = new InputStreamReader(xmlConn.getInputStream());
//build a buffered reader
BufferedReader xmlBuff = new BufferedReader(xmlStream);
//parse the data
xmlIn.parse(new InputSource(xmlBuff));
}
catch(SAXException se) { Log.e("AndroidTestsActivity",
"SAX Error " + se.getMessage()); }
catch(IOException ie) { Log.e("AndroidTestsActivity",
"Input Error " + ie.getMessage()); }
catch(Exception oe) { Log.e("AndroidTestsActivity",
"Unspecified Error " + oe.getMessage()); }
//return the parsed product list
return theViews;
}
}
最后,我的initialiseQuestions() 方法(来自其他工作 Activity )将提取的XML 数据分配给问题类(同样,未完成):
private void initialiseQuestions() {
// TODO Auto-generated method stub
questions = new Vector<Question>(); //Vector containing our questions
try
{
//create an instance of the QuestionHandler class
QuestionHandler handler = new QuestionHandler(getApplicationContext());
//get the string list by calling the public method
ArrayList<TextView> newViews = handler.getData();
//convert to an array
Object[] question = newViews.toArray();
//loop through the items, creating a View item for each
for(int i=0; i<question.length; i++)
{
//add the next question in the list
Question q1 = new Question(question[i]);
q1.addAnswer("Harold Godwin", false);
q1.addAnswer("Edward the Confessor", false);
q1.addAnswer("William the Conqueror", true);
q1.addAnswer("Alfred the Great", false);
questions.add(q1);
//mainLayout.addView((TextView)products[i]);
}
}
catch(Exception pce) { Log.e("AndroidTestsActivity", "PCE "+pce.getMessage()); }
我的主要问题是我不太明白我在做什么/需要在处理程序和initialiseQuestions 方法中进行更改。我不明白如何在处理程序中创建字符串(如果您只需要发回一个字符串数组,为什么需要 textViews?)并且我不明白如何在initialiseQuestions 中处理回数据。正如您所看到的, initaliseQuestions 方法应该采用解析后的 XML 并使用数据实例化一个问题对象。
有人可以告诉我我需要改变什么吗?
Here's the tutorial我一直在努力调整
最佳答案
解析 XML 确实是一项整洁的工作。有一个很好的图书馆Simple XML ,我们可以在Android中轻松使用。它是基于注释的库,有很好的教程。最好的事情是它直接从 XML 返回 POJO,并且在性能方面,它很好。
您所需要做的就是为您的 XML 创建一个基于注释的 POJO(请参阅网站上的教程)。使用 serializer.read(pojoClassType, xmlStr)
获取 POJO 的对象。
您还可以使用 Java 泛型概念仅使用一种通用方法来读取每个 XML 文件。就像,
public <T> T parseXML(Class<T> pojoType, String xmlStr){
//your code
}
关于java - 在 Android 中使用 SAX 解析 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13302358/
正如标题中所问,我有两个如下结构的 XML 文件 A.xml //here I want to include B.xml
我有一个 xml 文件。根据我的要求,我需要更新空标签,例如我需要更改 to .是否可以像那样更改标签.. 谢谢... 最佳答案 var xmlString=" "; var properStri
我有这样简单的 XML: Song Playing 09:41:18 Frederic Delius Violin Son
在我的工作中,我们有自己的 XML 类来构建 DOM,但我不确定应该如何处理连续的空格? 例如 Hello World 当它被读入 DOM 时,文本节点应该包含 Hello 和 World
我有以下 2 个 xml 文件,我必须通过比较 wd:Task_Name_ID 和 TaskID 的 XML 文件 2。 例如,Main XML File-1 wd:Task_Name_ID 具有以下
我在 Rails 应用程序中有一个 XML View ,需要从另一个文件插入 XML 以进行测试。 我想说“构建器,只需盲目地填充这个字符串,因为它已经是 xml”,但我在文档中看不到这样做的任何内容
我正在重建一些 XML 提要,因此我正在研究何时使用元素以及何时使用带有 XML 的属性。 一些网站说“数据在元素中,元数据在属性中。” 那么,两者有什么区别呢? 让我们以 W3Schools 为例:
在同一个文档中有两个 XML 声明是否是格式正确的 XML? hello 我相信不是,但是我找不到支持我的消息来源。 来自 Extensible Markup Language
我需要在包装器 XML 文档中嵌入任意(语法上有效的)XML 文档。嵌入式文档被视为纯文本,在解析包装文档时不需要可解析。 我知道“CDATA trick”,但如果内部 XML 文档本身包含 CDAT
XML 解析器和 XML 处理器是两个不同的东西吗?他们是两个不同的工作吗? 最佳答案 XML 解析器和 XML 处理器是一样的。它不适用于其他语言。 XML 是通用数据标记语言。解析 XML 文件已
我使用这个 perl 代码从一个文件中读取 XML,然后写入另一个文件(我的完整脚本有添加属性的代码): #!usr/bin/perl -w use strict; use XML::DOM; use
我正在编写一个我了解有限的历史脚本。 对象 A 的类型为 system.xml.xmlelement,我需要将其转换为类型 system.xml.xmldocument 以与对象 B 进行比较(类型
我有以下两个 XML 文件: 文件1 101 102 103 501 502 503
我有以下两个 XML 文件: 文件1 101 102 103 501 502 503
我有一个案例,其中一个 xml 作为输入,另一个 xml 作为输出:我可以选择使用 XSL 和通过 JAXB 进行 Unmarshalling 编码。性能方面,有什么真正的区别吗? 最佳答案 首先,程
我有包含 XML 的 XML,我想使用 JAXB 解析它 qwqweqwezxcasdasd eee 解析器 public static NotificationRequest parse(Strin
xml: mario de2f15d014d40b93578d255e6221fd60 Mario F 23 maria maria
尝试更新 xml 文件数组时出现以下错误。 代码片段: File dir = new File("c:\\XML"); File[] files = dir.listFiles(new Filenam
我怎样才能完成这样的事情: PS /home/nicholas/powershell> PS /home/nicholas/powershell> $date=(Get-Date | ConvertT
我在从 xml 文件中删除节点时遇到一些困难。我发现很多其他人通过各种方式在 powershell 中执行此操作的示例,下面的代码似乎与我见过的许多其他示例相同,但我没有得到所需的行为。 我的目标是将
我是一名优秀的程序员,十分优秀!