简体   繁体   English

JAVA DOM解析器解析XML文档

[英]Parsing XML document by JAVA DOM parser

I need to get some data from XML document and I am using XML parser.我需要从 XML 文档中获取一些数据,并且我正在使用 XML 解析器。 I was following this procedure and there is part of code:我正在遵循这个过程,并且有一部分代码:

File inputFile = new File("input.txt");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(inputFile);

After this there is more traversing in XML document and getting data.之后在 XML 文档中进行更多遍历并获取数据。 Since methods newDocumentBuilder() and parse() throws exceptions, they need to be placed inside try-catch block.由于方法 newDocumentBuilder() 和 parse() 会引发异常,因此需要将它们放在 try-catch 块中。 My question is : Should I put all my code inside try-catch block (also traversing and getting informations from XML - like in example on tutorialspoint.com), or can I put inside try-catch only these two methods:我的问题是:我是否应该将我的所有代码放入 try-catch 块中(也遍历并从 XML 获取信息 - 就像在 tutorialspoint.com 上的示例一样),或者我可以只将这两种方法放入 ZA75131CB1C90FC1C0A52AE241CDA

DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(inputFile);

What is the right solution?什么是正确的解决方案?

Thanks!谢谢!

You should handle the exception that are thrown from other call or declare it on your method.您应该处理从其他调用引发的异常或在您的方法中声明它。 The approach I always follow is to identify if an exception is thrown by programmer vs jvm and try to write programmer thrown exception inside try-catch block, this way I always have a benefit of adding custom code in catch block, it could be anything like adding some logging, etc to help debug your program when such exceptions are caught.我一直遵循的方法是确定程序员与 jvm 是否引发了异常,并尝试在 try-catch 块内编写程序员抛出的异常,这样我总是有在 catch 块中添加自定义代码的好处,它可以像添加一些记录等,以帮助在捕获此类异常时调试您的程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM