Java 解析两个同名元素-拉式解析器
我的最后一个问题措辞不当-我正在尝试解析以下xml: 我在解析拥塞位置内的元素时遇到问题:Java 解析两个同名元素-拉式解析器,java,android,xml,parsing,xmlpullparser,Java,Android,Xml,Parsing,Xmlpullparser,我的最后一个问题措辞不当-我正在尝试解析以下xml: 我在解析拥塞位置内的元素时遇到问题: <tns:camera> <tns:congestionLocations> <tns:congestion>Free Flow</tns:congestion> <tns:direction>Eastbound</tns:direction> <tns:order>6</tns:order>
<tns:camera>
<tns:congestionLocations>
<tns:congestion>Free Flow</tns:congestion>
<tns:direction>Eastbound</tns:direction>
<tns:order>6</tns:order>
</tns:congestionLocations>
<tns:congestionLocations>
<tns:congestion>Free Flow</tns:congestion>
<tns:direction>Westbound</tns:direction>
<tns:order>2</tns:order>
</tns:congestionLocations>
<tns:id>130</tns:id>
<tns:offline>false</tns:offline>
<tns:underMaintenance>false</tns:underMaintenance>
</tns:camera>
自由流动
东行
6.
自由流动
西行
2.
130
假的
假的
使用XMLPullParser,我可以读取id、offline等元素。这个很好用。我在下面编写了解析XML的代码:
// Get our factory and PullParser
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
XmlPullParser xpp = factory.newPullParser();
// Open up InputStream and Reader of our file.
FileInputStream fis = ctx.openFileInput("CameraSites.xml");
BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
// point the parser to our file.
xpp.setInput(reader);
// get initial eventType
int eventType = xpp.getEventType();
// Loop through pull events until we reach END_DOCUMENT
while (eventType != XmlPullParser.END_DOCUMENT) {
// Get the current tag
String tagname = xpp.getName();
// React to different event types appropriately
switch (eventType) {
case XmlPullParser.START_TAG:
if (tagname.equalsIgnoreCase(KEY_SITE)) {
// If we are starting a new <site> block we need
//a new CameraClass object to represent it
curCameraClass = new CameraClass();
}
break;
case XmlPullParser.TEXT:
//grab the current text so we can use it in END_TAG event
curText = xpp.getText();
break;
case XmlPullParser.END_TAG:
if (tagname.equalsIgnoreCase(KEY_SITE)) {
// if </site> then we are done with current Site
// add it to the list.
CameraSites.add(curCameraClass);
} else if (tagname.equalsIgnoreCase(KEY_ID)) {
curCameraClass.setID(curText);
} else if (tagname.equalsIgnoreCase(KEY_MAIN)) {
curCameraClass.setMAIN(curText);
}
break;
default:
break;
}
//move on to next iteration
eventType = xpp.next();
}
} catch (Exception e) {
e.printStackTrace();
}
// return the populated list.
return CameraSites;
}
//获取我们的工厂和PullParser
XmlPullParserFactory工厂=XmlPullParserFactory.newInstance();
XmlPullParser xpp=factory.newPullParser();
//打开文件的输入流和读取器。
FileInputStream fis=ctx.openFileInput(“CameraSites.xml”);
BufferedReader reader=新的BufferedReader(新的InputStreamReader(fis));
//将解析器指向我们的文件。
设置输入(读卡器);
//获取初始事件类型
int eventType=xpp.getEventType();
//循环拉取事件,直到到达END_文档
while(eventType!=XmlPullParser.END_文档){
//获取当前标记
字符串标记名=xpp.getName();
//对不同的事件类型做出适当的反应
开关(事件类型){
case XmlPullParser.START_标记:
if(标记名.equalsIgnoreCase(键位置)){
//如果我们要开始一个新的街区,我们需要
//一个新的CameraClass对象来表示它
curCameraClass=新的CameraClass();
}
打破
case XmlPullParser.TEXT:
//抓取当前文本,以便我们可以在END_标记事件中使用它
curText=xpp.getText();
打破
case XmlPullParser.END_标记:
if(标记名.equalsIgnoreCase(键位置)){
//如果这样,我们就完成了与当前网站
//将其添加到列表中。
添加(curCameraClass);
}else if(标记名.equalsIgnoreCase(键ID)){
curCameraClass.setID(curText);
}else if(标记名.equalsIgnoreCase(键\主)){
curCameraClass.setMAIN(curText);
}
打破
违约:
打破
}
//继续下一个迭代
eventType=xpp.next();
}
}捕获(例外e){
e、 printStackTrace();
}
//返回填充的列表。
返回喀麦隆;
}
我的问题是,我将如何解析拥塞位置中的拥塞和方向元素?我正在用一个类(CameraClass)将它们解析为get/set方法
提前谢谢 这是xml的代码
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.util.Log;
import android.view.Menu;
public class FileActivity extends Activity {
// Progress dialog
ProgressDialog pDialog;
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_file);
String data = "<tns:camera>"
+" <tns:congestionLocations>"
+"<tns:congestion>Free Flow</tns:congestion>"
+"<tns:direction>Eastbound</tns:direction>"
+"</tns:congestionLocations>"
+"<tns:congestionLocations>"
+"<tns:congestion>Free Flow</tns:congestion>"
+"<tns:direction>Westbound</tns:direction>"
+"</tns:congestionLocations>"
+"<tns:description>Bond St looking east</tns:description>"
+"<tns:direction>Eastbound</tns:direction>"
+"<tns:group>SH16-North-Western</tns:group>"
+"<tns:lat>-36.869</tns:lat>"
+"<tns:lon>174.746</tns:lon>"
+"<tns:name>SH16 1 Bond St</tns:name>"
+"<tns:viewUrl>http://www.trafficnz.info/camera/view/130</tns:viewUrl>"
+" </tns:camera>";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
new XmlParsing(data).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, new String[]{null});
else
new XmlParsing(data).execute(new String[]{null});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class XmlParsing extends AsyncTask<String, Void, String> {
// variables passed in:
String data;
// constructor
public XmlParsing(String data) {
this.data = data;
}
@Override
protected void onPreExecute() {
pDialog = ProgressDialog.show(FileActivity.this, "Fetching Details..", "Please wait...", true);
}
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder= dbFactory.newDocumentBuilder();
FileOutputStream out = openFileOutput("hello.txt",Context.MODE_PRIVATE);
out.write(data.getBytes());
out.close();
BufferedReader input = new BufferedReader(new InputStreamReader(openFileInput("hello.txt")));
StringBuffer inLine = new StringBuffer();
String text;
while ((text = input.readLine()) != null) {
inLine.append(text);
inLine.append("\n");
}
input.close();
String finalData =inLine.toString();
InputStream is = new ByteArrayInputStream(finalData.getBytes("UTF-8"));
Document doc = dBuilder.parse(is);
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("tns:camera");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
Element fstElmnt = (Element) node;
NodeList nameList = fstElmnt.getElementsByTagName("tns:group");
Element nameElement = (Element) nameList.item(0);
nameList = nameElement.getChildNodes();
Log.v("tns:group : "+((Node) nameList.item(0)).getNodeValue());
Element fstElmnt1 = (Element) node;
NodeList nameList1 = fstElmnt1.getElementsByTagName("tns:viewUrl");
Element nameElement1 = (Element) nameList1.item(0);
nameList1 = nameElement1.getChildNodes();
Log.v("tns:viewUrl : "+ ((Node) nameList1.item(0)).getNodeValue());
if(node.getNodeType() == Node.ELEMENT_NODE)
{
Element e = (Element) node;
NodeList resultNodeList = e.getElementsByTagName("tns:congestionLocations");
int resultNodeListSize = resultNodeList.getLength();
for(int j = 0 ; j < resultNodeListSize ; j++ )
{
Node resultNode = resultNodeList.item(j);
if(resultNode.getNodeType() == Node.ELEMENT_NODE)
{
Element fstElmnt2 = (Element) resultNode;
NodeList nameList2 = fstElmnt2.getElementsByTagName("tns:congestion");
Element nameElement2 = (Element) nameList2.item(0);
nameList2 = nameElement2.getChildNodes();
Log.v("tns:congestion", ""+((Node) nameList2.item(0)).getNodeValue());
Element fstElmnt3 = (Element) resultNode;
NodeList nameList3 = fstElmnt3.getElementsByTagName("tns:direction");
Element nameElement3 = (Element) nameList3.item(0);
nameList3 = nameElement3.getChildNodes();
Log.v("tns:direction--", ""+((Node) nameList3.item(0)).getNodeValue());
}
}
}
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
// Now we have your JSONObject, play around with it.
if (pDialog.isShowing())
pDialog.dismiss();
}
}
}
导入java.io.BufferedReader;
导入java.io.ByteArrayInputStream;
导入java.io.FileOutputStream;
导入java.io.IOException;
导入java.io.InputStream;
导入java.io.InputStreamReader;
导入java.net.MalformedURLException;
导入javax.xml.parsers.DocumentBuilder;
导入javax.xml.parsers.DocumentBuilderFactory;
导入javax.xml.parsers.parserConfiguration异常;
导入org.w3c.dom.Document;
导入org.w3c.dom.Element;
导入org.w3c.dom.Node;
导入org.w3c.dom.NodeList;
导入org.xml.sax.SAXException;
导入android.os.AsyncTask;
导入android.os.Build;
导入android.os.Bundle;
导入android.annotation.TargetApi;
导入android.app.Activity;
导入android.app.ProgressDialog;
导入android.content.Context;
导入android.util.Log;
导入android.view.Menu;
公共类FileActivity扩展活动{
//进度对话框
ProgressDialog;
@TargetApi(构建版本代码蜂窝)
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_文件);
String data=“”
+" "
+“自由流动”
+“东行”
+""
+""
+“自由流动”
+“西行”
+""
+“邦德街向东看”
+“东行”
+“SH16西北部”
+"-36.869"
+"174.746"
+“SH16 1邦街”
+"http://www.trafficnz.info/camera/view/130"
+" ";
if(Build.VERSION.SDK\u INT>=Build.VERSION\u code.HONEYCOMB)
新的XmlParsing(data).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,新字符串[]{null});
其他的
新建XmlParsing(data).execute(新字符串[]{null});
}
@凌驾
公共布尔onCreateOptions菜单(菜单){
//为菜单充气;这会将项目添加到操作栏(如果存在)。
getMenuInflater().充气(R.menu.main,menu);
返回true;
}
公共类XmlParsing扩展了异步任务{
//传入的变量:
字符串数据;
//建造师
公共XML解析(字符串数据){
这个数据=数据;
}
@凌驾
受保护的void onPreExecute(){
pDialog=ProgressDialog.show(FileActivity.this,“获取详细信息…”,“请稍候…”,true);
}
@凌驾
受保护的字符串doInBackground(字符串…参数){
//TODO自动生成的方法存根
试试{
DocumentBuilderFactory dbFactory=DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder=dbFactory.newDocumentBuilder();
FileOutputStream out=openFileOutput(“hello.txt”,Context.MODE\u PRIVATE);
out.write(data.getBytes());
out.close();
BufferedReader input=新的BufferedReader(新的InputStreamReader(openFileInput(“hello.txt”));
串缓冲