4

私はJavaが初めてで、現在のURL http://belbooner.site40.net/testXmls/details.xmlでhttpを使用して1つのxmlファイルを解析するタスクがあります

Dom メソッドを使用して解析するクラスを作成しましたが、1 つのノード値を取得しようとしているときに java.lang.NullPointerException が発生しました。コードは次のとおりです。

import java.security.KeyStore.Builder;
import java.util.*;
import java.io.*;
import java.net.*;
import javax.swing.text.Document;
import javax.xml.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.w3c.dom.*;
import org.w3c.dom.CharacterData;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;


public class RequestResponse {
    public static void main(String[] args) throws ParserConfigurationException, IOException, SAXException {
        URL url = new URL("http://belbooner.site40.net/testXmls/details.xml");
        RequestResponse req= new RequestResponse();
        req.getHTTPXml(url);
    }

     void getHTTPXml(URL url) throws ParserConfigurationException, IOException, SAXException {

                //URL url = new URL("http://belbooner.site40.net/testXmls/details.xml");
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("POST");
                conn.setRequestProperty("ACCEPT","application/xml");
                InputStream xml = conn.getInputStream();


                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                DocumentBuilder builder = factory.newDocumentBuilder();
                org.w3c.dom.Document document = builder.parse(xml);

                System.out.println(document);
                String doctype = conn.getContentType(); 
                System.out.print(doctype);

                NodeList root = document.getChildNodes();

                Node server = getNodes("server",root);
                Node check = getNodes("check", server.getChildNodes());
                NodeList nodes = check.getChildNodes();

                String checkid= getNodeValue("checkid", nodes);
                System.out.println(checkid);


                conn.disconnect();  

                //return (Document) DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(xml);


     }


    Node getNodes(String tagName, NodeList nodes) {
        for(int i=0; i< nodes.getLength();i++) {
            Node node= nodes.item(i);
            if(node.getNodeName().equalsIgnoreCase(tagName)) {
                return node;
            }

        }
        return null;
    }

    String getNodeValue(String tagName, NodeList nodes ) {
        for ( int i = 0; i < nodes.getLength(); i++ ) {
            Node node = nodes.item(i);
            if (node.getNodeName().equalsIgnoreCase(tagName)) {
                NodeList childNodes = node.getChildNodes();
                for (int y = 0; y < childNodes.getLength(); y++ ) {
                     Node data = childNodes.item(y);
                     if ( data.getNodeType() == Node.TEXT_NODE ) {
                         return data.getNodeValue();
                     }
                     if(data instanceof CharacterData) {
                         CharacterData cd= (CharacterData) data;
                         return cd.getData();
                     }
                 }

            }
        }
        return "";
    }








    }

私が得ているスタックトレースは次のとおりです。

application/xmlException in thread "main" java.lang.NullPointerException at 
RequestResponse.getHTTPXml(RequestResponse.java:45) at
RequestResponse.main(RequestResponse.java:22)

Node server = getNodes("server",root);`に変更した後

    Node resultNode = getNodes("result", root);
    Node server = getNodes("server", resultNode.getChildNodes());`

   `application/xmlException in thread "main" java.lang.NullPointerException
        at RequestResponse.getHTTPXml(RequestResponse.java:49)
        at RequestResponse.main(RequestResponse.java:22)

`

問題を見つけるのを手伝ってください。

4

2 に答える 2

3

問題は、Node server = getNodes("server",root);nullを返すことです。

なぜこれが起こるのですか?getNodesをどのように実装したかよく見てください

Node getNodes(String tagName, NodeList nodes) {
    for(int i=0; i< nodes.getLength();i++) {
        Node node= nodes.item(i);
        if(node.getNodeName().equalsIgnoreCase(tagName)) {
            return node;
        }
    }
    return null;
}

単一の「結果」ノードであるドキュメントルートを入力として指定し、それを反復処理して、ノードの名前がこの場合は「サーバー」であるかどうかを比較します。したがって、nullを返し、NPEを取得します。

ノードのルックアップは、次の方法で実行する必要があります。

 NodeList root = document.getChildNodes();
// Keep in mind that you have the following structure:
// result
//   server
//    checks
//     check
//      checkId
//     check
//      checkId

Node resultNode = getNodes("result", root);
Node server = getNodes("server", resultNode.getChildNodes());
Node checks = getNodes("checks", server.getChildNodes());
NodeList childNodes = checks.getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
    Node possibleCheck = childNodes.item(i);
    if (possibleCheck.getNodeName().equals("check")) {
    String checkid = getNodeValue("checkid", possibleCheck.getChildNodes());
    System.out.println(checkid);
    }
}

このようにして、正しいノードリストを反復処理します。

于 2012-11-30T08:44:33.650 に答える
2

XPathを使用すると、xmlの解析中に(通常の反復よりも)効率的かつ柔軟になります。

IBMXPathリファレンスのXPathチュートリアル
Oriellyチュートリアル
XpathリファレンスOraclejavaチュートリアル

以下のコードを試してください。

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class RequestResponse {
    public static void main(String[] args) throws ParserConfigurationException,
            IOException, SAXException {
        URL url = new URL("http://belbooner.site40.net/testXmls/details.xml");
        RequestResponse req = new RequestResponse();
        req.getHTTPXml(url);
    }

    void getHTTPXml(URL url) throws ParserConfigurationException, IOException,
            SAXException {
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("ACCEPT", "application/xml");
        InputStream xml = conn.getInputStream();

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        org.w3c.dom.Document document = builder.parse(xml);

        System.out.println(document);
        String doctype = conn.getContentType();
        System.out.println(doctype);

        XPathFactory pathFactory = XPathFactory.newInstance();
        XPath path = pathFactory.newXPath();
        XPathExpression expression;
        try {
            expression = path.compile("/result/server/checks/check/checkid");
            NodeList nodeList = (NodeList) expression.evaluate(document,
                    XPathConstants.NODESET);

            String checkids[] = getNodeValue(nodeList);
            for (String checkid : checkids) {
                System.out.print(checkid + ", ");
            }

        } catch (XPathExpressionException e) {
            e.printStackTrace();
        }
        conn.disconnect();

    }

    String[] getNodeValue(NodeList nodes) {
        String checkIds[] = new String[nodes.getLength()];
        for (int i = 0; i < nodes.getLength(); i++) {
            Node node = nodes.item(i);
            checkIds[i] = node.getTextContent();
        }
        return checkIds;
    }

} 
于 2012-11-30T09:10:47.410 に答える