You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用DocumentBuilderFactory.parse()返回Null Document的问题求助

Why does DocumentBuilderFactory.parse() seem to return a null Document?

First off, let's clear up a critical misunderstanding: DocumentBuilder.parse() will never return null. According to Java's official docs, this method either returns a valid Document object or throws an exception (like IOException, SAXException, etc.). The null you're seeing in your output is actually from dom.getElementById("1"), not the dom object itself.

Let's break down the issues and fixes step by step:

  • Why does dom.getElementById("1") return null?

    1. Your XML file doesn't have any element with an id="1" attribute right now—your file only contains a single <address> element with no attributes at all.
    2. Even if you added an id attribute to the element, the DOM parser doesn't automatically recognize arbitrary id attributes as ID-type. To make getElementById() work, you need to:
      • Add a DTD declaration to your XML to explicitly mark the id attribute as an ID:
        <!DOCTYPE address [
          <!ELEMENT address (#PCDATA)>
          <!ATTLIST address id ID #REQUIRED>
        ]>
        <address id="1">idk just filler for now</address>
        
      • Or enable validation in your parser configuration:
        dbf.setValidating(true);
        
  • Your getTextValue call has a logical error

    dom.getDocumentElement() returns the root element of your XML, which is already the <address> element. When you call getTextValue(address, doc, "address"), you're trying to find a child <address> element inside the root <address>—which doesn't exist. That's why your address variable ends up null.

    To get the text content of the root <address> element directly, use:

    address = doc.getTextContent();
    
  • Improve your exception handling

    Right now you only print the exception message, which can be vague or empty in some cases. Print the full stack trace instead to catch hidden issues like file permission problems or XML encoding errors:

    catch (ParserConfigurationException pce) {
        pce.printStackTrace();
    } catch (SAXException se) {
        se.printStackTrace();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
    

内容的提问来源于stack exchange,提问作者user9211520

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:08:03