我使用下面的脚本,输出为
X值:123
Y值:123
X值:123
Y值:130
如何将第一个X设置为X0;首先Y为Y0,第二个X为X1,第二个Y为Y1?我使用SAX解析器,它已正确处理我的输入文件,现在我想定义X0,X1,Y0,Y1以画线
public static void main(String argv[]) {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
DefaultHandler handler = new DefaultHandler() {
boolean xele = false;
boolean yele = false;
public void startElement(String uri, String localName,String qName,
Attributes attributes) throws SAXException {
if (qName.equalsIgnoreCase("X")) {
xele = true;
}
if (qName.equalsIgnoreCase("Y")) {
yele = true;
}
}
public void characters(char ch[], int start, int length) throws SAXException {
if (xele) {
System.out.println("X value : " + new String(ch, start, length));
xele = false;
}
if (yele) {
System.out.println("Y value : " + new String(ch, start, length));
yele = false;
}
}
};
saxParser.parse("c:\\input.xml", handler);
} catch (Exception e) {
e.printStackTrace();
}
由于
答案 0 :(得分:0)
在DefaultHandler实现中,每次characters
方法被解析器调用时,您可以声明数组以保存X和Y的值以及在存储值之后递增的索引,并通过getter公开这些数组。或者,您可以使用java.util.List
/ java.util.ArrayList
等集合来保存值。
public static void main(String argv[])
{
try
{
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
MyDefaultHandler handler = new MyDefaultHandler();
saxParser.parse("c:\\input.xml", handler);
System.out.println(handler.getXList() + ", " + handler.getYList());
}
catch (Exception e)
{
e.printStackTrace();
}
}
static class MyDefaultHandler extends DefaultHandler
{
private List<Integer> xList = new ArrayList<Integer>();
private List<Integer> yList = new ArrayList<Integer>();
boolean xele = false;
boolean yele = false;
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException
{
if (qName.equalsIgnoreCase("X"))
{
xele = true;
}
if (qName.equalsIgnoreCase("Y"))
{
yele = true;
}
}
public void characters(char ch[], int start, int length) throws SAXException
{
if (xele)
{
System.out.println("X value : " + new String(ch, start, length));
xele = false;
xList.add(Integer.parseInt(new String(ch, start, length)));
}
if (yele)
{
System.out.println("Y value : " + new String(ch, start, length));
yele = false;
yList.add(Integer.parseInt(new String(ch, start, length)));
}
}
public List<Integer> getXList()
{
return xList;
}
public List<Integer> getYList()
{
return yList;
}
};