简体   繁体   中英

Building DOM document from xml string gives me a null document

I'm trying to use the DOM library to parse a string in xml format. For some reason my document contains nulls and I run into issues trying to parse it. The string variable 'response' is not null and I am able to see the string when in debug mode.

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        InputSource is = new InputSource(new StringReader(response));
        Document doc = builder.parse(is);

        NodeList nodes = doc.getElementsByTagName("BatchFile");;
        for (int i = 0; i < nodes.getLength(); i++) {
            Element element = (Element) nodes.item(i);

            NodeList batchItem = element.getChildNodes();
            String uri = batchItem.item(0).getNodeValue();
            String id = batchItem.item(1).getNodeValue();
            String fqName = batchItem.item(2).getNodeValue();
          }

Highlighting over the line Document doc = builder.parse(is); after it has run shows the result of [#document: null] .

Edit: I've managed to not got an empty doc now but the string values are still null (at end of code). How would I get the value of something like this

        <GetBatchFilesResult>
            <BatchFile>
                <Uri>uri</Uri>
                <ID>id</ID>
                <FQName>file.zip</FQName>
            </BatchFile>

        </GetBatchFilesResult>

You can also use getTextContent(). getNodeValue will return null for elements. Besides, you'd better use getElementsByTagName, since white spaces are also treated as one of the child nodes.

Element element = (Element) nodes.item(i);
String uri = element.getElementsByTagName("Uri").item(0).getTextContent();
String id =  element.getElementsByTagName("ID").item(0).getTextContent();
String fqName =  element.getElementsByTagName("FQName").item(0).getTextContent();

Check Node API document to see what type of nodes will return null for getNodeValue.

I found the solution. Seems stupid that you have to do it this way to get a value from a node.

        Element element = (Element) nodes.item(i);

        NodeList batchItem = element.getChildNodes();
        Element uri = (Element) batchItem.item(0);
        Element id = (Element) batchItem.item(1);
        Element fqName = (Element) batchItem.item(2);
        NodeList test = uri.getChildNodes();
        NodeList test1 = id.getChildNodes();
        NodeList test2 = fqName.getChildNodes();

        String strURI= test.item(0).getNodeValue();
        String strID= test1.item(0).getNodeValue();
        String strFQName= test2.item(0).getNodeValue();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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