java - 向 child 添加appendChild时遇到问题

标签 java xml dom

我正在尝试使用 Java 和 org.w3c.dom 制作一些简单的 XML,但是当我尝试将一个子项附加到一个子项时,我陷入了困境,如下所示:

<root>
     <child>
          <childOfTheChild>Some text</childOfTheChild>
     </child>
</root>

我尝试了一些变体(例如首先附加子项然后创建 childOfTheChild 等):

Element root = doc.getDocumentElement();

Element child = doc.createElement("child");
Element childOfTheChild = doc.createElement("childOfTheChild ");

Text st = doc.createTextNode("Some text");

childOfTheChild.appendChild(st);
child.appendChild(childOfTheChild );

root.appendChild(child);

我总是得到相同的结果,即:

<root>
     <child>null</child>
</root>

此代码是否有问题,或者可能是其他问题?

编辑:

打印功能在某些测试 XML 中工作正常,否则... 所以,没有进行一些美容校正的功能:

//Call System.out.println( print(dokument.getFirstChild()) );
private String print(Node node) {

    String txt = "";  //xml string presentation

    //Get the primary node name and any existing attributes, like <myNode att1='some val'>
    if (node.getNodeType() == node.ELEMENT_NODE) 
    {
        //The name
        txt += "<" + node.getNodeName();

        //Insert the attributes
        if (node.hasAttributes()) 
        {
            NamedNodeMap atts = node.getAttributes();
            for (int i = 0; i < atts.getLength(); i++) {
                Node atts = atts.item(i);
                txt += " " + atts.getNodeName() + " = '" + atts.getNodeValue() + "'";
            }
        }
        txt +=  ">\n";
    }

    int nChilds = -1;

    //Get any existing child nodes, so the <root><child1></child1></root>
    if (node.hasChildNodes()) 
    {
        NodeList childs = node.getChildNodes();
        nChilds  = childs.getLength();


        if (nChilds == 1) 
        {
            txt += childs.item(0).getNodeValue();
        } 
        else 
        {
            for (int j = 0; j < nChilds; j++) {
                txt += print(childs.item(j));
            }
        }
    }

    //And the ending of the primary node, like </root>
    if (node.getNodeType() == node.ELEMENT_NODE) 
    {
        txt += "</" + node.getNodeName();
        txt +=  ">\n";
    }
    return txt;
}

最佳答案

适合我吗?:

import static org.junit.Assert.assertTrue;

import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.junit.Test;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;

public class DomTest {

    @Test
    public void testDom() throws Exception {
        Document document = createEmptyDocument();

        Element root = document.getDocumentElement();
        Element child = document.createElement("child");
        Element childOfTheChild = document.createElement("childOfTheChild");
        Text st = document.createTextNode("Some text");
        childOfTheChild.appendChild(st);
        child.appendChild(childOfTheChild);
        root.appendChild(child);

        assertTrue(serialise(document).contains("Some text"));
    }

    private Document createEmptyDocument() throws ParserConfigurationException {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DOMImplementation domImpl = dbf.newDocumentBuilder()
                .getDOMImplementation();
        Document document = domImpl.createDocument(null, "root", null);
        return document;
    }

    private String serialise(Document document)
            throws TransformerFactoryConfigurationError,
            TransformerConfigurationException, TransformerException {
        TransformerFactory xff = TransformerFactory.newInstance();
        Transformer xf = xff.newTransformer();
        StringWriter sw = new StringWriter();
        xf.transform(new DOMSource(document), new StreamResult(sw));
        return sw.toString();
    }
}

关于java - 向 child 添加appendChild时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/857555/

相关文章:

java - 处理请求时发生异常 : java.net.URISyntaxException:绝对 URI 中的相对路径

java - Netty 线程被阻塞

java - 如何从字符串中提取以下模式?

iphone - 核心动画xml或json框架

xml - XML 元素名称中包含的 XSLT 命名空间 URI

java - glReadPixel 返回零和错误 1282 (Android)

c# - 将报告重新绑定(bind)到新的 XML XSD

javascript - getElementById 仍然是 "safe"DOM 操作方法

c# - 如何在 C# 中获取 HTMLAgilityPack DOM 元素的边界框?

javascript - 根据表中单击/滚动的行填充输入框