2011-04-26 27 views
6

Necesito crear un objeto de documento XML utilizando NodeList. ¿Puede alguien por favor ayudarme a hacer esto? Te he mostrado el código y el código XML siguienteCrear documento XML utilizando nodeList

import 
javax.xml.parsers.DocumentBuilderFactory; 
import javax.xml.xpath.*; import 
org.w3c.dom.*; 

public class ReadFile { 

    public static void main(String[] args) { 
     String exp = "/configs/markets"; 
     String path = "testConfig.xml"; 
     try { 
      Document xmlDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(path); 
      XPath xPath = XPathFactory.newInstance().newXPath(); 
      XPathExpression xPathExpression = xPath.compile(exp); 
      NodeList nodes = (NodeList) 
       xPathExpression.evaluate(xmlDocument, 
             XPathConstants.NODESET); 

     } catch (Exception ex) { 
      ex.printStackTrace(); 
     } 
    } 
} 

archivo XML se muestra a continuación

<configs> 
    <markets> 
     <market> 
      <name>Real</name> 
     </market> 
     <market> 
      <name>play</name> 
     </market> 
    </markets> 
</configs> 

Gracias de antemano ..

Respuesta

12

debe hacerlo de esta manera:

  • se crea una nueva org.w3c.dom.Document newXmlDoc donde se almacenan los nodos en su NodeList,
  • se crea un nuevo elemento raíz, y lo añaden a newXmlDoc
  • entonces, para cada nodo n en su NodeList, importar n en newXmlDoc, y luego anexar n como un hijo de root

Aquí está el código:

public static void main(String[] args) { 
    String exp = "/configs/markets/market"; 
    String path = "src/a/testConfig.xml"; 
    try { 
     Document xmlDocument = DocumentBuilderFactory.newInstance() 
       .newDocumentBuilder().parse(path); 

     XPath xPath = XPathFactory.newInstance().newXPath(); 
     XPathExpression xPathExpression = xPath.compile(exp); 
     NodeList nodes = (NodeList) xPathExpression. 
       evaluate(xmlDocument, XPathConstants.NODESET); 

     Document newXmlDocument = DocumentBuilderFactory.newInstance() 
       .newDocumentBuilder().newDocument(); 
     Element root = newXmlDocument.createElement("root"); 
     newXmlDocument.appendChild(root); 
     for (int i = 0; i < nodes.getLength(); i++) { 
      Node node = nodes.item(i); 
      Node copyNode = newXmlDocument.importNode(node, true); 
      root.appendChild(copyNode); 
     } 

     printTree(newXmlDocument); 
    } catch (Exception ex) { 
     ex.printStackTrace(); 
    } 
} 

public static void printXmlDocument(Document document) { 
    DOMImplementationLS domImplementationLS = 
     (DOMImplementationLS) document.getImplementation(); 
    LSSerializer lsSerializer = 
     domImplementationLS.createLSSerializer(); 
    String string = lsSerializer.writeToString(document); 
    System.out.println(string); 
} 

La salida es:

<?xml version="1.0" encoding="UTF-16"?> 
<root><market> 
      <name>Real</name> 
     </market><market> 
      <name>play</name> 
     </market></root> 

Algunas notas:

  • he cambiado exp a /configs/markets/market, porque sospecho que desea copiar los elementos market, en lugar de la única markets elemento
  • para la printXmlDocument, he utilizado el código interesante en este answer

Espero que esto ayude.


Si no desea crear un nuevo elemento raíz, entonces puede usar su expresión XPath original, que devuelve un NodeList que consta de un solo nodo (tener en cuenta que el XML debe tener una sola raíz elemento) que puede agregar directamente a su nuevo documento XML.

Ver siguiente código, donde les comentaba líneas del código anterior:

public static void main(String[] args) { 
    //String exp = "/configs/markets/market/"; 
    String exp = "/configs/markets"; 
    String path = "src/a/testConfig.xml"; 
    try { 
     Document xmlDocument = DocumentBuilderFactory.newInstance() 
       .newDocumentBuilder().parse(path); 

     XPath xPath = XPathFactory.newInstance().newXPath(); 
     XPathExpression xPathExpression = xPath.compile(exp); 
     NodeList nodes = (NodeList) xPathExpression. 
     evaluate(xmlDocument,XPathConstants.NODESET); 

     Document newXmlDocument = DocumentBuilderFactory.newInstance() 
       .newDocumentBuilder().newDocument(); 
     //Element root = newXmlDocument.createElement("root"); 
     //newXmlDocument.appendChild(root); 
     for (int i = 0; i < nodes.getLength(); i++) { 
      Node node = nodes.item(i); 
      Node copyNode = newXmlDocument.importNode(node, true); 
      newXmlDocument.appendChild(copyNode); 
      //root.appendChild(copyNode); 
     } 

     printXmlDocument(newXmlDocument); 
    } catch (Exception ex) { 
     ex.printStackTrace(); 
    } 
} 

esto le dará el siguiente resultado:

<?xml version="1.0" encoding="UTF-16"?> 
<markets> 
     <market> 
      <name>Real</name> 
     </market> 
     <market> 
      <name>play</name> 
     </market> 
    </markets> 
+0

funciona bien Marco.Pero el problema es que hay un elemento llamado raíz que no está originalmente en el documento xml. ¿Hay alguna manera de hacerlo sin tener el elemento raíz? Gracias de antemano – nath

+0

, necesita un elemento raíz en un XML. Lo que podría hacer es extraer 'markets' con su XPath original (' String exp = "/ configs/markets"; '), y luego su' NodeList' contendrá un solo nodo, que podrá importar y agregar directamente a su nuevo XML documento: vea la respuesta editada. – MarcoS

+0

gracias Marco. Ahora funciona bien :) :) – nath

0

puede probar el método de DocumentadoptNode().

Tal vez necesite iterar sobre su NodeList. Puede acceder al individuo Nodes con nodeList.item(i).

Si desea envolver sus resultados de búsqueda en un Element, puede utilizar createElement() de la Document y appendChild() en el recién creado Element

Cuestiones relacionadas