2009-05-13 6 views
0

J'essaye de faire du XML simple avec Java et org.w3c.dom, mais je me suis coincé quand j'ai essayé d'ajouter un enfant à un enfant, quelque chose comme ça:J'ai des problèmes avec appendChild à un enfant

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

J'ai essayé pas mal de variations de ce (comme le premier enfant et l'annexant que la création childOfTheChild etc.):

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); 

et je reçois toujours le même résultat, qui est:

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

Y a-t-il un problème dans ce code ou peut-être autre chose?

Edit:

fonction d'impression fonctionne bien avec certains tests XMLs autrement ... Ainsi, la fonction sans quelques corrections de beauté:

//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; 
} 
+0

Comment imprimez-vous votre document sur la console? – toolkit

+0

Alors, quel était le problème? :) – willcodejavaforfood

+0

La fonction d'impression, commentez sous la réponse :). –

Répondre

2

fonctionne bien pour moi ?:

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(); 
    } 
} 
+0

OK, merci! Il semble que la fonction d'impression de la mienne a quelques erreurs, va déboguer :). Cela signifie plus que l'exercice dom, c'est pourquoi c'est comme si ce n'était pas avec la sérialisation. Merci encore! –

+0

Remarque: Une alternative à l'approche Transformer de la sérialisation consiste à utiliser DOM-LS. Voir http://stackoverflow.com/questions/620250/java-domimplementationls – toolkit

Questions connexes