Java XMLStreamException,检查缺少的结束标记

时间:2015-07-27 07:52:28

标签: java xml tags

在给定的XML文件中,我需要检查每个起始标记是否有结束标记

如果找不到结束标记,我想用行号和标记名称给出错误消息

我设法这样做但是异常仍然显示在控制台中..我怎么才能显示错误消息?

缺少人员结束标记的示例xml文件:

<company>
<staff>
        <name>john</name>
        <area>area1</area>
        <city>city1</city>
        <initials>js</initials>

</company>

代码:

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Stack;

import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;



public class trial {

public static void main(String[] args) throws FileNotFoundException, XMLStreamException {

    InputStream is = new FileInputStream("C:/Users/IBM_ADMIN/Desktop/comparison.xml");
    XMLInputFactory inputFactory = XMLInputFactory.newInstance();
    XMLEventReader eventReader = inputFactory.createXMLEventReader(is, "utf-8");
    Stack<StartElement> stack = new Stack<StartElement>();
    while (eventReader.hasNext()) {
        try {
            XMLEvent event = eventReader.nextEvent();
            if (event.isStartElement()) {
                StartElement startElement = event.asStartElement();
                System.out.println("processing element: " + startElement.getName().getLocalPart());
                stack.push(startElement);
            }
            if(event.isEndElement()){
                stack.pop();
            }
        }catch(XMLStreamException e){

            System.out.println("error in line: " +e.getLocation().getLineNumber());
            StartElement se = stack.pop();
            System.out.println("non-closed tag:" + se.getName().getLocalPart() + " " + se.getLocation().getLineNumber());

            throw e;
        }
    }


}



}

1 个答案:

答案 0 :(得分:0)

Exception方法中抛出main()意味着如果你自己不这样做,JVM必须抓住它,并且它很可能不知道该怎么做,所以你看到错误打印并可能执行中止。 Read about main() throwing errors here.

您需要的只是注释掉

throw e;

因为您已经处理了异常。