I'm trying to build an XML representation of some data. 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. 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() .
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,小型且非常快速。
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.