Java DOM解析器不解析一行XML



我有这个一行xml文件(没有缩进和新行)如下

    <?xml version="1.0" encoding="UTF-8"?>
    <Document xmlns="urn:iso:std:iso:20022:tech:xsd:camt.054.001.03" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="urn:iso:std:iso:20022:tech:xsd:camt.054.001.03 
camt.054.001.03.xsd">
    <BkToCstmrDbtCdtNtfctn><GrpHdr><MsgId>0000000006</MsgId>
<CreDtTm>2013-04-
    16T14:38:00</CreDtTm>
</GrpHdr>
</BkToCstmrDbtCdtNtfctn></Document>

我正在使用这个java DOM解析器程序来解析和检索值

import java.io.File;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
public class GetNodeValues {
    static String value = null;
    static ArrayList alist = null;
    /****************** GET XPATH FOR EACH TAG **************************************/
    public static String getXPath(Element elemnt) {
        String xpath = null;
        String curNode = elemnt.getNodeName();
        ArrayList<String> al = new ArrayList<String>();
        al.add(curNode);
        // al.add(parNode);
        while (!elemnt.getParentNode().getNodeName().equals("#document")) {
            al.add(elemnt.getParentNode().getNodeName());
            elemnt = (Element) elemnt.getParentNode();
        }
        for (int i = al.size() - 1; i >= 0; i--) {
            xpath = xpath + "/" + al.get(i);
        }
        return xpath.replaceAll("null", "");
    }
    /******************************************************************************************/
    /**************************** GET TAG NAMES AND VALUES ***********************/
    public static ArrayList getValues() {
        try {
            alist = new ArrayList();
            String xmlFile = "C:/Users/Administrator/Desktop/sample2.xml";
            File file = new File(xmlFile);
            if (file.exists()) {
                // Create a factory
                DocumentBuilderFactory factory = DocumentBuilderFactory
                        .newInstance();
                // Use the factory to create a builder
                DocumentBuilder builder = factory.newDocumentBuilder();
                Document doc = builder.parse(xmlFile);
                doc.getDocumentElement().normalize();
                // Get a list of all elements in the document
                NodeList list = doc.getElementsByTagName("*");
                for (int i = 0; i < list.getLength(); i++) {
                    // Get element
                    Element element = (Element) list.item(i);
                    String nodnam = element.getNodeName();

                    if (element.getChildNodes().getLength() > 0) // then it has
                                                                    // text
                    {
                        String val = element.getChildNodes().item(0)
                                .getNodeValue();
                        if (val.startsWith("n")) { // Discarding pseudo nodes
                        } else {
                            value = nodnam + " > " + val + " > "
                                    + getXPath(element); // print node names and
                                                            // values
                            System.out.println(value);
                            alist.add(value);
                        }
                    }
                }
            } else {
                System.out.print("File not found!");
            }
        } catch (Exception e) {
            System.exit(1);
        }
        return alist;
    }
    /********************************************************************************************/
    /************************** MAIN METHOD **********************************************/
    public static void main(String[] args) {
        System.out.println(getValues());
    }
}

它没有打印任何值。但是,如果我编辑xml文件并像这样添加缩进和新行

<?xml version="1.0" encoding="UTF-8"?>
<Document xmlns="urn:iso:std:iso:20022:tech:xsd:camt.054.001.03" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:iso:std:iso:20022:tech:xsd:camt.054.001.03 camt.054.001.03.xsd">
    <BkToCstmrDbtCdtNtfctn>
        <GrpHdr>
            <MsgId>0000000006</MsgId>
            <CreDtTm>2013-04-16T14:38:00</CreDtTm>
        </GrpHdr>
    </BkToCstmrDbtCdtNtfctn>
</Document>

则得到如下输出

MsgId > 0000000006 > /Document/BkToCstmrDbtCdtNtfctn/GrpHdr/MsgId
CreDtTm > 2013-04-16T14:38:00 > /Document/BkToCstmrDbtCdtNtfctn/GrpHdr/CreDtTm

所以问题是我不能编辑每一个xml文件作为no。要处理的文件是巨大的。我错过了什么在java dom解析器?我所需要的只是程序应该解析和打印没有缩进和新行....

的xml文件的值。

注意:

} catch (Exception e) {
     System.exit(1);
}

你在隐藏异常,而不能看到真正的问题。至少打印堆栈跟踪信息,如:

} catch (Exception e) {
     e.printStackTrace();
     System.exit(1);
}

在这种情况下,String val = element.getChildNodes().item(0).getNodeValue();中的var可以为空。因此,使用以下修复程序应该可以解决此问题:

String val = element.getChildNodes().item(0).getNodeValue();
if (val != null) {
   if (val.startsWith("n")) { // Discarding pseudo nodes
   } else {
       value = nodnam + " > " + val + " > "
            + getXPath(element); // print node names and
                                // values
       System.out.println(value);
       alist.add(value);
  }
}

除了导致NPE的实际问题外,我认为您的代码目前存在3个明显的问题:

  } catch (Exception e) {
     System.exit(1);
  }

第一个问题(正如@dan所指出的)是您没有打印堆栈跟踪。

第二个问题是您正在捕获Exception。在大多数情况下,这是一个坏主意,因为你最终会捕捉到各种意想不到的异常……除了你可能期待的。最好是只捕获您期望并可以处理的异常。其余的应该允许传播。

第三个问题是,你调用System.exit似乎是一个实用程序方法。这是一个坏主意,原因如下:

  • 在方法中退出将使该方法难以在其他上下文中使用…

  • 任何调用System的方法。退出对单元测试来说很棘手。如果你不采取措施避免它(例如,使用一个mock框架,可以"模拟"调用),该方法将导致JVM运行单元测试停止…立即.

在我看来,正确的代码编写方法是:

  1. getValues()方法声明中添加任何必要的throws子句,并且
  2. try ... catch放到main方法中…当然,还需要一些代码来输出或记录异常堆栈跟踪。

最新更新