简体   繁体   English

构建XML文档:我做错了

[英]Building an XML Document: I'm doing it wrong

I'm trying to build an XML representation of some data. 我正在尝试建立一些数据的XML表示形式。 I've followed other examples, but I can't get it working. 我遵循了其他示例,但无法正常运行。 I've commented code down to this basic bit, and still nothing. 我已经将代码注释到了这个基本位,仍然一无所获。 This code compiles and runs OK, but the resulting output is empty. 该代码将编译并运行正常,但结果输出为空。 A call to dDoc.getDocumentElement() returns null. 调用dDoc.getDocumentElement()会返回null。 What am I doing wrong? 我究竟做错了什么?

Please help me, Stack Overflow. 请帮助我,堆栈溢出。 You're my only hope. 你是我唯一的希望。

        DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();
        dFactory.setValidating( false );
        DocumentBuilder dBuilder = dFactory.newDocumentBuilder();
        Document dDoc = dBuilder.newDocument();

        // The root document element.
        Element pageDataElement = dDoc.createElement("page-data");
        pageDataElement.appendChild(dDoc.createTextNode("Example Text."));

        dDoc.appendChild(pageDataElement);

        log.debug(dDoc.getTextContent());

The following runs ok. 以下运行正常。 You just need to call dDoc.getDocumentElement().getTextContent() instead of dDoc.getTextContent() . 您只需要调用dDoc.getDocumentElement()。getTextContent()而不是dDoc.getTextContent()即可

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class Demo {

    public static void main(String[] args) throws Exception {
        DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance(); 
        dFactory.setValidating( false ); 
        DocumentBuilder dBuilder = dFactory.newDocumentBuilder(); 
        Document dDoc = dBuilder.newDocument(); 

        // The root document element. 
        Element pageDataElement = dDoc.createElement("page-data"); 
        pageDataElement.appendChild(dDoc.createTextNode("Example Text.")); 

        dDoc.appendChild(pageDataElement); 

        System.out.println(dDoc.getDocumentElement().getTextContent());
    }
}

Will give the output: 将给出输出:

Example Text. 示例文字。

您还可以使用http://xom.nu/。Xom具有更好的API,小型且非常快速。

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

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