SAX 解析器不会读取和打印我的 xml 文件的一部分

发布于 2024-12-02 21:56:27 字数 4882 浏览 3 评论 0原文

我真的需要有人帮助我的解析器读取并仅显示 xml 文件的一部分,我可以从上到下读取两次,但是当我尝试使用 xml 处理程序中的内部标签将每个部分分开时它不执行此操作,而是会在脑海中显示其中的一点内容

这是我的解析器的代码

package heavytime
import java.net.URL;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

//import android.content.Intent;
import android.os.Bundle;
//import android.view.View;
//import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

public class Mainweather extends Seskanoreweatherpart2Activity {

weatherlist sitesList = null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main2);

     LinearLayout layout = new LinearLayout(this);
     layout.setOrientation(1);
     layout.setBackgroundColor(0xFF000080);

     TextView value [];

    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.seskanore.com/currentoutput.xml");


        /** Create handler to handle XML Tags ( extends DefaultHandler ) */
        XMLhandler XMLhandler = new XMLhandler();
        xr.setContentHandler(XMLhandler);
        xr.parse(new InputSource(sourceUrl.openStream()));

        } catch (Exception e) {
        System.out.println("XML Pasing Excpetion = " + e);
        }

        /** Get result from XMLhandler SitlesList Object */
        sitesList = XMLhandler.sitesList;

        /** Assign textview array lenght by arraylist size */
   //       item = new TextView[sitesList.getName().size()];
        value = new TextView[sitesList.getName().size()];

        /** Set the result text in textview and add it to layout */
        for (int i = 0; i < sitesList.getName().size(); i++) {
        value[i] = new TextView(this);
        value[i].setText(sitesList.getvalue().get(i)+ " is "           +sitesList.getitem().get(i));

        layout.addView(value[i]);

         }


        /** Set the layout view to display */
        setContentView(layout);
 }
 }

这是我的 XML 处理程序的代码

package heavytime
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class XMLhandler extends DefaultHandler {

Boolean currentElement = false;
Boolean temperature = false;
String currentValue = null;
//  int currentVal = 0;
public static weatherlist sitesList = null;

public static weatherlist getSitesList() {
return sitesList;
}

public static void setSitesList(weatherlist sitesList) {
XMLhandler.sitesList = sitesList;
}

 @Override
    public void startDocument() throws SAXException {
        // Some sort of setting up work
    } 

@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {

    currentElement = true;

if (localName.equals("weatherdata"))
{
    sitesList = new weatherlist();}
else if (localName.equals("item")){
        temperature = true;
        String attr = attributes.getValue("name");
        sitesList.setValue(attr);}


}



/** Called when tag closing*/
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {

currentElement = false;

/** set value*/ 
if (localName.equals("temperaturetags")){
    localName.equalsIgnoreCase("item");
    sitesList.setName(currentValue);
    localName.equalsIgnoreCase("value");
    sitesList.setitem(currentValue);

}


temperature = false;
}

/** Called to get tag characters*/
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {

if (currentElement) {
currentValue = new String(ch, start, length);
currentElement = false;
}
}

@Override
public void endDocument() throws SAXException {
    // Some sort of finishing up work
}   
}

这是我的 Arraylist 的用于显示解析信息的代码

    package heavytime
    import java.util.ArrayList;


    public class weatherlist {

private ArrayList<String> value = new ArrayList<String>();
private ArrayList<String> name = new ArrayList<String>();
private ArrayList<String> item = new ArrayList<String>();

/** In Setter method default it will return arraylist
* change that to add */

public ArrayList<String> getvalue() {
return value;
}

public void setValue(String value) {
this.value.add(value);
}

public ArrayList<String> getName() {
return name;
}

public void setName(String name) {
this.name.add(name);
}

public ArrayList<String> getitem() {
return item;
}

public void setitem(String item) {
this.item.add(item);
}

  }

我希望它只显示其中的标签温度标签,但我尝试了一切并且似乎没什么用 有人可以帮助我吗

非常感谢

I really need someone help in trying to get my parser to read and show just one section of xml file, i can get it two read from top to bottom but when i try and use the inner tags in my xml handler that separate each section out it doesn't do it and goes mental and shows one bit of it

This is the code for my Parser

package heavytime
import java.net.URL;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

//import android.content.Intent;
import android.os.Bundle;
//import android.view.View;
//import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

public class Mainweather extends Seskanoreweatherpart2Activity {

weatherlist sitesList = null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main2);

     LinearLayout layout = new LinearLayout(this);
     layout.setOrientation(1);
     layout.setBackgroundColor(0xFF000080);

     TextView value [];

    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.seskanore.com/currentoutput.xml");


        /** Create handler to handle XML Tags ( extends DefaultHandler ) */
        XMLhandler XMLhandler = new XMLhandler();
        xr.setContentHandler(XMLhandler);
        xr.parse(new InputSource(sourceUrl.openStream()));

        } catch (Exception e) {
        System.out.println("XML Pasing Excpetion = " + e);
        }

        /** Get result from XMLhandler SitlesList Object */
        sitesList = XMLhandler.sitesList;

        /** Assign textview array lenght by arraylist size */
   //       item = new TextView[sitesList.getName().size()];
        value = new TextView[sitesList.getName().size()];

        /** Set the result text in textview and add it to layout */
        for (int i = 0; i < sitesList.getName().size(); i++) {
        value[i] = new TextView(this);
        value[i].setText(sitesList.getvalue().get(i)+ " is "           +sitesList.getitem().get(i));

        layout.addView(value[i]);

         }


        /** Set the layout view to display */
        setContentView(layout);
 }
 }

This is the code for my XML handler

package heavytime
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class XMLhandler extends DefaultHandler {

Boolean currentElement = false;
Boolean temperature = false;
String currentValue = null;
//  int currentVal = 0;
public static weatherlist sitesList = null;

public static weatherlist getSitesList() {
return sitesList;
}

public static void setSitesList(weatherlist sitesList) {
XMLhandler.sitesList = sitesList;
}

 @Override
    public void startDocument() throws SAXException {
        // Some sort of setting up work
    } 

@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {

    currentElement = true;

if (localName.equals("weatherdata"))
{
    sitesList = new weatherlist();}
else if (localName.equals("item")){
        temperature = true;
        String attr = attributes.getValue("name");
        sitesList.setValue(attr);}


}



/** Called when tag closing*/
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {

currentElement = false;

/** set value*/ 
if (localName.equals("temperaturetags")){
    localName.equalsIgnoreCase("item");
    sitesList.setName(currentValue);
    localName.equalsIgnoreCase("value");
    sitesList.setitem(currentValue);

}


temperature = false;
}

/** Called to get tag characters*/
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {

if (currentElement) {
currentValue = new String(ch, start, length);
currentElement = false;
}
}

@Override
public void endDocument() throws SAXException {
    // Some sort of finishing up work
}   
}

This the Code for my Arraylist for displaying the parsed information

    package heavytime
    import java.util.ArrayList;


    public class weatherlist {

private ArrayList<String> value = new ArrayList<String>();
private ArrayList<String> name = new ArrayList<String>();
private ArrayList<String> item = new ArrayList<String>();

/** In Setter method default it will return arraylist
* change that to add */

public ArrayList<String> getvalue() {
return value;
}

public void setValue(String value) {
this.value.add(value);
}

public ArrayList<String> getName() {
return name;
}

public void setName(String name) {
this.name.add(name);
}

public ArrayList<String> getitem() {
return item;
}

public void setitem(String item) {
this.item.add(item);
}

  }

I want it to display just the tags within the temperature tags but ive tried everything and nothing seems to work
Can someone please help me

Much appreciated

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

才能让你更想念 2024-12-09 21:56:27

您犯了一个常见的错误,即假设在解析器的一对 startElementendElement 调用之间仅调用 characters 方法一次并在开始标签和结束标签之间提供中间内容。它实际上可以被调用很多次,并且每次调用只包含部分内容。

正确的处理是在 startElement 方法中创建或附加某种类型的累加器(通常是 StringBuilderStringBuffer),在字符方法中累加到其中,然后在 endElement 方法中使用和处置或分离它。

我认为您的代码中还有更多错误,但这可能是使其正常工作的开始。

为了仅处理特定标签内的项目,您需要设置一个布尔标志,表示您在看到该标签时在 startElement 方法中找到了它,在 endElement 中将其设置为 false对于标签,并在从任何其他标签收集数据之前测试该标志。您需要对 中的每个子标签使用上述过程,因为它们包含字符数据。

为了我自己的娱乐,并希望它可以帮助您更好地理解这一切,我编写了一个小处理程序,用于将 下的数据收集到地图列表中。

package com.donroby;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class WeatherHandler extends DefaultHandler {

    private List<Map<String,String>> result = new ArrayList<Map<String,String>>();
    private Map<String,String> currentItem;
    private boolean collectingItems;
    private boolean collectingItem;
    private StringBuilder builder;

    public List<Map<String,String>> getResult() {
        return result;
    }

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        if (qName.equals("temperaturetags")) {
            collectingItems = true;
        }
        else if (qName.equals("item") && collectingItems) {
            currentItem = new HashMap<String,String>();
            currentItem.put("name", attributes.getValue("name"));
            collectingItem = true;
        }
        else if (collectingItem) {
            builder = new StringBuilder();
        }
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        if (qName.equals("temperaturetags")) {
            collectingItems = false;
        }
        if (qName.equals("item") && collectingItems) {
            result.add(currentItem);
            currentItem = null;
            collectingItem = false;
        }
        else if (collectingItem) {
            currentItem.put(qName,  builder.toString());
            builder = null;
        }
    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        if (collectingItem &&(builder != null)) {
           builder.append(ch, start, length);
        }
    }
}

对于实际使用,我更有可能创建一个域对象并将其收集到该类的列表中,但这会使代码有点膨胀,超出了我想要做的快速示例。

You're making the common mistake of assuming that the characters method will be called only once between a pair of startElement and endElement calls from the parser and supply the entore content between the start and end tags. It can actually be called many times, and each call contains only part of the content.

The proper handling is to create or attach an accumulator of some sort (commonly a StringBuilder or StringBuffer) in the startElement method, accumulate into it in the characters method, and then to use and dispose or detach it in the endElement method.

I think there's a good bit more wrong in your code, but this may be a start toward getting it working.

In order to process only the items within a particular tag, you'll want to set a boolean flag connoting that you've found it in the startElement method on seeing that tag, set it false in the endElement for the tag, and test that flag before collecting data from any other tags. You'll need to use the process described above for each of the subtags withing <item>, as they contain their data as characters.

For my own amusement, and in hopes that it might help you understand all this a bit better, I've written a little handler that collects the data under <temperaturetags> into a list of maps.

package com.donroby;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class WeatherHandler extends DefaultHandler {

    private List<Map<String,String>> result = new ArrayList<Map<String,String>>();
    private Map<String,String> currentItem;
    private boolean collectingItems;
    private boolean collectingItem;
    private StringBuilder builder;

    public List<Map<String,String>> getResult() {
        return result;
    }

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        if (qName.equals("temperaturetags")) {
            collectingItems = true;
        }
        else if (qName.equals("item") && collectingItems) {
            currentItem = new HashMap<String,String>();
            currentItem.put("name", attributes.getValue("name"));
            collectingItem = true;
        }
        else if (collectingItem) {
            builder = new StringBuilder();
        }
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        if (qName.equals("temperaturetags")) {
            collectingItems = false;
        }
        if (qName.equals("item") && collectingItems) {
            result.add(currentItem);
            currentItem = null;
            collectingItem = false;
        }
        else if (collectingItem) {
            currentItem.put(qName,  builder.toString());
            builder = null;
        }
    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        if (collectingItem &&(builder != null)) {
           builder.append(ch, start, length);
        }
    }
}

For real use, I would more likely create a domain object and collect into a list of that class, but that would bloat the code a bit beyond what I wanted to do for a quick sample.

空‖城人不在 2024-12-09 21:56:27

characters() 函数中,使用 String.trim(),然后在继续之前检查是否 String.length()>0

然后在 startElement()处使用 stack 模型以及 push()pop() 数据endElement() 事件分别

In characters() function, use String.trim() and then check if String.length()>0 before proceeding.

Then use a stack model and push() and pop() data at startElement() and endElement() events respectively

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文