XML NodeList getElementsByTagName

I found a problem when I'm trying to use the "getElementsByTagName" method to get
a XML Node when the node name is the Root node!
The getElementsByTagName method returns a list of nodes (NodeList type)
and its only one parameter is the name of the tag (node) you want to find in a XML structure!
When the node I want to find is the root , the method don't return nothing! getLength() == 0!!
I don't understand why this occurs! and I don't know how can I solve this problem.
For instance:
You have the XML:
<city>
<street>
<name>John</name>
</street>
</city>
if a use the method like this: getElementsByTagName("city")
I get 0 items inside the NodeList when it should be 1, the root element.
any solution !?
Best!
Bruno
NodeList getElementsByTagName

try getDocumentElement to get root element and then get nodelist.

Similar Messages

  • How to read an attribute of an xml tag in jsp.

    hi guys,
    This is murali krishna. i have a small problem,
    i have one xml file (books.xml)
    <?xml version="1.0" encoding="iso-8859-1"?>
    <library>
    <book id="1">
    <name>Head First Java, 2nd Edition</name>
    <author>Kathy Sierra and Bert Bates</author>
    <publication-date>09-Feb-2005</publication-date>
    </book>
    <book id="2">
    <name>Effective Java</name>
    <author>Joshua Bloch</author>
    <publication-date>28-May-2008</publication-date>
    </book>
    <book id="3">
    <name>Java How to Program, 7th Edition</name>
    <author>Harvey M. Deitel and Paul J. Deitel</author>
    <publication-date>6-Jan-2007</publication-date>
    </book>
    </library>
    I tried to read this xml file in jsp as shown below
    <%@ page language="java" %>
    <%@ page import="org.w3c.dom.*" %>
    <%@ page import="javax.xml.parsers.DocumentBuilder" %>
    <%@ page import="javax.xml.parsers.DocumentBuilderFactory" %>
    <%
    DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
    DocumentBuilder db =dbf.newDocumentBuilder();
    Document doc=db.parse("c:\\books.xml");
    NodeList nl = doc.getElementsByTagName("book");
    %>
    <html>
    <head>
    <title>How to read XML file in JAVA</title>
    </head>
    <body>
    <%
    for(int i=0;i<nl.getLength();i++)
    NodeList nameNlc= doc.getElementsByTagName("name");
    Element nameElements=(Element)nameNlc.item(i);
    String nameTagValue=nameElements.getChildNodes().item(0).getNodeValue();
    NodeList authorNlc= doc.getElementsByTagName("author");
    Element authorElements=(Element)authorNlc.item(i);
    String authorTagValue=authorElements.getChildNodes().item(0).getNodeValue();
    NodeList dateNlc= doc.getElementsByTagName("publication-date");
    Element dateElements=(Element)dateNlc.item(i);
    String dateTagValue=dateElements.getChildNodes().item(0).getNodeValue();
    out.println("name :"+nameTagValue+"<br>");
    out.println("author :"+authorTagValue+"<br>");
    out.println("publication-date :"+dateTagValue+"<br><br>");
    %>
    </body>
    </html>
    so, my problem is I was unable to read the attribute of the tag book , that is "id".
    can any one tell me how to read this "id" attribute.
    Murali Krishna
    [email protected]

    hi,
    U r retriving the elements by tag name.So it just chks the tag name ie.<book> & gives u array of elements.But u need retrive d attribute of <book> tag itself.
    =Solution =====
    Add one more statement ----> var[]= doc.getElementsByName("book");
    Now u hav book elements as an array & can retrive id in for loop
    for(var; var.length;var++)
    doc.element[var].id.value

  • Creating an XML File

    I'm using this code to build an XML file and to write it on a file:
        DBConnect(); //connection to an Access DB
        StringBuffer sql = new StringBuffer();
        sql.append("SELECT * FROM atleti ORDER BY id");
        try{
          rs = st.executeQuery(sql.toString());             
          Document doc = XMLTool.parse("myXMLFile.xml");   
          NodeList nl = doc.getElementsByTagName("giocatori");
          Node node = nl.item(0);
            //Node root = doc.createElement("giocatori");
          while(rs.next()){
            Node n = doc.createElement("giocatore");
            Node n2 = doc.createElement("id");
            Node t2 = doc.createTextNode(rs.getString("id"));
            n2.appendChild(t2);
            n.appendChild(n2);
            Node n4 = doc.createElement("cognome");
            Node t4 = doc.createTextNode(rs.getString("cognome"));
            n4.appendChild(t4);
            n.appendChild(n4);
            Node n3 = doc.createElement("nome");
            Node t3 = doc.createTextNode(rs.getString("Nome"));
            n3.appendChild(t3);
            n.appendChild(n3);
            Node n5 = doc.createElement("codicefiscale");
            Node t5 = doc.createTextNode(rs.getString("codicefiscale"));
            n5.appendChild(t5);
            n.appendChild(n5);
            Node n6 = doc.createElement("tesserasanitaria");
            Node t6 = doc.createTextNode(rs.getString("tesserasanitaria"));
            n6.appendChild(t6);
            n.appendChild(n6);
         Node n7 = doc.createElement("cartaidentita");
            Node t7 = doc.createTextNode(rs.getString("cartaidentita"));
            n7.appendChild(t7);
            n.appendChild(n7);
            Node n8 = doc.createElement("luogonascita");
            Node t8 = doc.createTextNode(rs.getString("luogonascita"));
            n8.appendChild(t8);
            n.appendChild(n8);
            Node n9 = doc.createElement("datanascita");
            Node t9 = doc.createTextNode(rs.getString("datanascita").substring(0,10));
            n9.appendChild(t9);
            n.appendChild(n9);
            Node n10 = doc.createElement("indirizzo");
           Node n11 = doc.createElement("residente");     
              Node t11 = doc.createTextNode(rs.getString("residente"));
              n11.appendChild(t11);
           n10.appendChild(n11);
           Node n12 = doc.createElement("via");     
              Node t12 = doc.createTextNode(rs.getString("indirizzo"));
              n12.appendChild(t12);
              n10.appendChild(n12);
           Node n13 = doc.createElement("cap");     
              Node t13 = doc.createTextNode(rs.getString("cap"));
              n13.appendChild(t13);
              n10.appendChild(n13);
         n.appendChild(n10);
            Node n14 = doc.createElement("telefono");
           Node n16 = doc.createElement("fisso");     
              Node t16 = doc.createTextNode(rs.getString("telefonofisso"));
              n16.appendChild(t16);
              n14.appendChild(n16);
           Node n15 = doc.createElement("cellulare");     
              Node t15 = doc.createTextNode(rs.getString("telefonocellulare"));
              n15.appendChild(t15);     
              n14.appendChild(n15);      
         n.appendChild(n14);
            Node n17 = doc.createElement("email");
            Node t17 = doc.createTextNode(rs.getString("email"));
            n17.appendChild(t17);
            n.appendChild(n17);
            Node n18 = doc.createElement("squadra");
           Node n19 = doc.createElement("categoria");     
              Node t19 = doc.createTextNode(" ");
              n19.appendChild(t19);
              n18.appendChild(n19);
           Node n20 = doc.createElement("numero");     
              Node t20 = doc.createTextNode("0");
              n20.appendChild(t20);     
              n18.appendChild(n20);      
         n.appendChild(n18);
            node.appendChild(n);
            //node.normalize();
          //System.out.println(node);
          FileWriter fw = new FileWriter("OutputFile.xml");
          fw.write(node.toString());
          fw.flush();
          fw.close();I have 2 problems:
    a) The output file is writed all on one line and I would like to have it indented so it will be more readable and "cool".
    b) I have this error "null Text data??" and I don't know its mind!
    Could anybody help me?

    hi,
    for a commercial grade app , u should rather
    have a reusable method.
      public static void createXfile(Document doc, String filePath)
         FileOutputStream fos =null;
         try{
              File f = new File(filePath);
              OutputFormat of = new OutputFormat("XML","ISO-8859-1",true);
              of.setIndent(1);
              of.setIndenting(true);
              fos = new FileOutputStream(f);
              XMLSerializer printer = new XMLSerializer(fos, of);
              printer.asDOMSerializer();
              printer.serialize(doc);
              fos.close();
         catch(Exception e){
              //u wont reach this place until u messup something
              // real bad
              Logger.log("XUtil----------"+e.getMessage(), Logger.ERROR);
       dont go for transformer just for printing DOM.
    HTH
    vasanth-ct

  • Problem in reading XML contents

    Hi all,
    I have a problem in extracting a portion of the XML file.
    the XML is
    <x>
         <y1></y1>
         <y2>
              <value1>One</value1>
              <value2>Two</value2>
              <value3>Three</value3>     </y2>
         <y3></y3>
    </x>the code i have written is
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import org.w3c.dom.Document;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    public class DOMParserDemo
        public static void main(String s[]){
            try{
                DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
                Document document = docBuilder.parse("doc.xml");
                NodeList nodeList = document.getElementsByTagName("y2");
                Node node = nodeList.item(0);
                NodeList nList = node.getChildNodes();
                int len = nList.getLength();
                for(int i=0; i<len; i++){
                    System.out.println(nList.item(i).getNodeName());
            }catch(Exception e){
                e.printStackTrace();
    } I got the result as.
    #text
    value1
    #text
    value2
    #text
    value3
    #text
    where i expect the value to be prinited in the place of #text
    can any one please help me to display the content correctly.
    thanks in advance
    subra

    This gets the element's contents - using concat from the other thread - you just need to navigate down the tree to the right depth:      NodeList nodeList = document.getElementsByTagName("y2");
          // for every y2 element
          for (int index1 = 0, length1 = nodeList.getLength(); index1 < length1; index1++) {
            final Element y2 = (Element)nodeList.item(index1);
            final NodeList y2Children = y2.getChildNodes();
            // for every child of a y2 element
            for (int index2 = 0, length2 = y2Children.getLength(); index2 < length2; index2++) {
              final Node child = y2Children.item(index2);
              // if that child node is an element node
              if (child.getNodeType() == Node.ELEMENT_NODE) {
                Element element = (Element)child;
                // print it's name, and the concatenation of any text nodes nested in it
                System.out.println(concat(element.getChildNodes(),
                                          new StringBuffer(element.getNodeName()).append(" = ")));
          }Pete

  • Read xml file in another web server

    my question is how to read xml file that in another web server???
    my existing code look like that, where the xml file is situated in C drive.
    <%@ page contentType="text/html"%>
    <%@ page import="javax.xml.parsers.DocumentBuilderFactory,
              javax.xml.parsers.DocumentBuilder,
              org.w3c.dom.*"
    %>
    <%
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse("c:/xml/message.xml");
    NodeList nl = doc.getElementsByTagName("message");
    %>
    <html>
    <body>
    <%= nl.item(0).getFirstChild().getNodeValue() %>
    </body>
    </html>

    are you looking for this?
    Document doc = db.parse("http://myotherwebserver/myFile.xml");

  • XML Parser returning XML content

    This probably seems like overkill..
    Im building a JSP that reads in XML and parses it. I then need to filter for specific values in the XML, and return a chunk of the XML to the output stream.
    So far I've got..
          //set-up in and content-type
            FileInputStream file = new FileInputStream (getServletContext().getRealPath("/games_arcade/xml/game_marketing_content.xml"));
            //response.setContentType("text/xml");
            //parse the request
            Document doc = null ;
            try {
                   DocumentBuilderFactory docBuilderFact = DocumentBuilderFactory.newInstance();
                   DocumentBuilder docBuilder = docBuilderFact.newDocumentBuilder();
                   doc = docBuilder.parse(file);
                   out.println("Go on ya good thing!!!");
            } catch (ParserConfigurationException pcEx) {
                throw new ServletException("jaxp not configured!", pcEx);
            //get needed data from the xml
            NodeList games = doc.getElementsByTagName("game");
              out.println(output.toString());
              Now Im lost. All the requisites are there, imports etc, Im just stuck with filtering the NodeList.
    Or am I completely wrong with this approach?
    Any help greatly appreciated.
    thanks!
    Stephen

    Hi,
    thanks for the replyand suggestions. Have a bit of an issue with this method, this method (due to technical limitations) is completely JSP, using a standard iPlanet 6.1 classpath. I cant deploy WAR's (and cant use taglibs). Xpath/XSL would be ideal, but how do I write the output as XML?
    So are you suggesting
    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
      <xsl:output method="html"/>
        <xsl:template match="/">
            <xsl:for-each select="games/game">
              <xsl:if test="@id = $GAMEID">
                   ... output the xml node using value-of's etc...
              </xsl:if>
            </xsl:for-each>
          </xsl:template>
        </xsl:stylesheet>Cheers Dr Clap!
    Stephen

  • Append data and save in XML

    hi all ! I have some data that is stored in a XML fine and since each SML is client based it can be edited according to everyone tastes. So my question is, can someone point me out how to append data and then saving it into the XML (hopefully without having to rewrite the whole XML document.
    This is how Im retreiving my Data from the XML and my try at appending data, but I dont know if Im being succesfull because its not being saved:
    String path = "C:/MedPro";
                    File file = new File(path + "/XML/data.xml");
                    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                    DocumentBuilder db = dbf.newDocumentBuilder();
                    Document doc = db.parse(file);
                    doc.getDocumentElement().normalize();
                    /* PARA ALIMENTAR LA AGENDA CON LOS DATOS DEL XML*/
                    NodeList nodeLst = doc.getElementsByTagName("Agenda"); //Lista de Items para manejar la agenda
                    for (int s = 0; s < nodeLst.getLength(); s++) {
                        Node fstNode = nodeLst.item(s);
                        if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
                            Element fstElmnt = (Element) fstNode;
                            NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("sub");
                            Element fstNmElmnt = (Element) fstNmElmntLst.item(0);
                            Node nod=fstNmElmntLst.item(0).appendChild(doc.createTextNode("Hola"));
                            /*NodeList fstNm = fstNmElmnt.getChildNodes();
                            System.out.println("Agenda : " + ((Node) fstNm.item(0)).getNodeValue());
                            lista_agenda.add(s, ((Node) fstNm.item(0)).getNodeValue());*/
                    }Any help is appreciated.
    Thanks a lot!
    Edited by: juanmanuelsanchez on Oct 10, 2009 4:27 PM

    juanmanuelsanchez wrote:
    ok but is there a way to do it without having to rewrite the whole XML?short answer, no. xml, like many structured file formats, is not really amenable to "partial updating". the only way to "append" data to a file without rewriting it is to write to the end of the file. how will you maintain a valid xml format by only adding to the end of the file? i can't imagine the xml is that large seeing as you are using a DOM parser to read it, so i don't understand why you don't want to just rewrite the file.

  • How to parse this xml

    Hi Guys
    I have the following xml file.
    <scms:TokenDescription xmlns:scms="http://www./schema/2003/07/Passage/scms.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" Name="SID33322800" ATR="asdfafasdfdafdasfsda" FormatVersion="1.0">
      <Token SerialNumber="123456789" SmartChipSN="3232323232">
        <KeySetVersion>99</KeySetVersion>
        <SecurityDomainAID>fdfasfsadfsdaf</SecurityDomainAID>
        <AuthenticationKey>fdasfdasfdsafsda</AuthenticationKey>
        <MACKey>fdasfdsafdsaf</MACKey>
        <KeyEncryptionKey>asdfasdfasdfsdafa</KeyEncryptionKey>
        <DefaultPUK>fdsafsdafsdfdsafasd</DefaultPUK>
      </Token>
    </scms:TokenDescription>I have managed to read the xml fine and bind it manuall to an object as follows:
                DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
                Document doc = docBuilder.parse (new File("xml.xml"));
                        NodeList keySetVersion = firstPersonElement.getElementsByTagName("KeySetVersion");
                        Element firstNameElement = (Element)keySetVersion.item(0);
                        NodeList textFNList = firstNameElement.getChildNodes();
                        System.out.println("keySetVersion : " +
                               ((Node)textFNList.item(0)).getNodeValue().trim());My Question is can anyone tell me how i can read this part of the xml from this document the serial number and smartChipSN
    <Token SerialNumber="123456789" SmartChipSN="3232323232">

    Try this code,
    Nodelist nList = doc.getElementByTagName("Token ") ;
    Element node = (Element)nList.item(0);
    To read the values of "SerialNumber" and "SmartChipSN", you can use getAttribute method.
    String serailNo = node.getAttribute("SerialNumber");
    String chipSN = node.getAttribute("SmartChipSN");

  • Reading XML using Java

    I want to read all <temp >nodes map them to some variable and create one more XML.
    I am stuck up in the first place itself where i need to read the data :( . I am getting null pointer exception, please find the code also.
    <?xml version="1.0" encoding="UTF-8"?>
    <ftpl id="47" name="XXXXXXXX xxx xxxxxxxx">
    <abc-cab name="Systems" id="43434">
    <abc-dr name="zzzzz" id="4545454">
    <temp key="Type">null</param>
    <temp key="Folder">/ZVZ/XXXXX - xyz</param>
    <temp key="Author">XYZ,ABC</param>
    <temp key="Comments">null</param>
    <temp key="Mailed_By">XYZ,ABC</param>
    <temp key="Subject">null</param>
    <temp key="Key_Words">null</param>
    <abc-page name="1" id="3524012">
    <file text="/asas/asasa/asa/asas/Oxxxxxx2276744.txt" count="1"/>
    </abc-page>
    </abc-dr>
    </abc-cab>
    </ftpl>
    try {
    File file = new File("source-file");
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(file);
    doc.getDocumentElement().normalize();
    System.out.println("Root element " + doc.getDocumentElement().getNodeName());
    NodeList nodeLst = doc.getElementsByTagName("abc-dr");
    for (int s = 0; s < nodeLst.getLength(); s++) {
    Node fstNode = nodeLst.item(s);
    if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
    Element fstElmnt = (Element) fstNode;
    NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("abc-dr");
    Element fstNmElmnt = (Element) fstNmElmntLst.item(1);
    NodeList fstNm = fstNmElmnt.getChildNodes();
    System.out.println("First Node : " + ((Node) fstNm.item(1)).getNodeValue());
    NodeList lstNmElmntLst = fstElmnt.getElementsByTagName("Folder");
    Element lstNmElmnt = (Element) lstNmElmntLst.item(0);
    NodeList lstNm = lstNmElmnt.getChildNodes();
    } catch (Exception e) {
    e.printStackTrace();
    Please help.. let me know the code which read XML I have tried with all SAX/DOM i am getting same NUllPointerExcetion
    Message was edited by:
    JavaNewUser

    Hi
    Thanks patricknz
    pls find the XMl and the java code
    I have again modified the code .. but got the same result as below
    [temp: null]----------------------param =
    [temp: null]----------------------param =
    [temp: null]----------------------param =
    [temp: null]----------------------param =
    [temp: null]----------------------param =
    [temp: null]----------------------param =
    [temp: null]----------------------param =
    [abc-page: null]----------------------abc-page=
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import org.w3c.dom.Document;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    import org.w3c.dom.Element;
    import java.lang.*;
    public class SampleDOM
        public static void main(String s[]){
            try{
                DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
                Document document = docBuilder.parse("C:\\demo.xml");
                   NodeList nodeList = document.getElementsByTagName("abc-dr");
          for (int i = 0, length1 = nodeList.getLength(); i < length1; i++) {
            final Element rDoc = (Element)nodeList.item(i);
            final NodeList rDocC = rDoc.getChildNodes();
            for (int j = 0, length2 = rDocC.getLength(); j < length2; j++) {
              final Node child = rDocC.item(j);
            if (child.getNodeType() == Node.ELEMENT_NODE) {
                Element element = (Element)child;
                System.out.println(element.getChildNodes() + "----------------------" +
                                          new StringBuffer(element.getNodeName()).append(" = "));
            }catch(Exception e){
                e.printStackTrace();
    }XML FIle:-
    <?xml version="1.0" encoding="UTF-8"?>
    <ftpl id="47" name="XXXXXXXX xxx xxxxxxxx">
         <abc-cab name="Systems" id="43434">
              <abc-dr name="zzzzz" id="4545454">
                   <temp key="Type">null</param>
                   <temp key="Folder">/ZVZ/XXXXX - xyz</param>
                   <temp key="Author">XYZ,ABC</param>
                   <temp key="Comments">null</param>
                   <temp key="Mailed_By">XYZ,ABC</param>
                   <temp key="Subject">null</param>
                   <temp key="Key_Words">null</param>
                   <abc-page name="1" id="3524012">
                        <file text="/asas/asasa/asa/asas/Oxxxxxx2276744.txt" count="1"/>
                   </abc-page>
              </abc-dr>
         </abc-cab>
    </ftpl>Message was edited by:
    JavaNewUser
    Message was edited by:
    JavaNewUser

  • Parse XML fail

    I want to parse following xml file
    <?xml version="1.0" encoding="UTF-8" ?>
    <table count='2'>
       <row>
          <id>
             <![CDATA[1]]>
          </id>
          <type>
             <![CDATA[income]]>
          </type>
         <money>
             <![CDATA[234]]>
         </money>     
         <as_sortIndex>1</as_sortIndex>
       </row>
       <row>
          <id>
              <![CDATA[2]]>
          </id>
          <type>
             <![CDATA[outcome]]>
          </type>
          <money>
             <![CDATA[108]]>
          </money>     
          <as_sortIndex>2</as_sortIndex>
       </row>
    </table>Parse code is follows,when I run it,I find I can't print xml value,where is wrong? Thanks
    <%@ page language="java" contentType="text/html;charset=UTF-8"%>
    <%@ page import="javax.xml.parsers.*"%>
    <%@ page import="javax.xml.transform.*"%>
    <%@ page import="javax.xml.transform.dom.*"%>
    <%@ page import="javax.xml.transform.stream.*"%>
    <%@ page import="org.w3c.dom.*"%>
    <%@ page import="java.io.*"%>
    <%
         DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
         DocumentBuilder parser=factory.newDocumentBuilder();
         Document doc=parser.parse(application.getRealPath("/")+new File("test.xml"));
         NodeList nlist=doc.getElementsByTagName("table");
         Element node=(Element)nlist.item(0);
         String v=node.getElementsByTagName("row").item(0).getFirstChild().getNodeValue();
         System.out.println("=="+v);
    %>

    I think u should first change the CDATA NODES of xml to TEXT Nodes. Then you try to parse this.
    try the following code to change the CDATA nodes to TEXT nodes.
    ==================================================
    public static void main(String[] args) throws Exception {      
    getinputFile(youXMLfile); // "yourXMLfile" is the file object of the input xml file with CDATA nodes
    public void getinputFile(File f) throws Exception{
              File inputfile = new File("inputXMlFile.xml");
              DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance();
    dbfactory.setCoalescing(true);
    DocumentBuilder db = dbfactory.newDocumentBuilder();
    Document doc = db.parse(inputfile);
    new ConvertingCDATANodesTextNodes().CDATAtextnode(doc);
    public void CDATAtextnode(Document doc) throws Exception {
    TransformerFactory factory = TransformerFactory.newInstance();
    Transformer transformer = factory.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    StringWriter sw = new StringWriter();
    StreamResult result = new StreamResult(sw);
    DOMSource source = new DOMSource(doc);
    transformer.transform(source, result);
    String xmlfile = sw.toString();
    System.out.println("xml file = "+xmlfile);
    ==================================================
    Hope it will solve your problem

  • Class to support XML Config.

    Hi ,
    I have a system that loads your properties trough a class that reads an xml file. For example ans sysconfig.xml that holds all of the system properties. Now, i need to load xml properties to another class, for example an class that read files from another application, and i need to store password, login, path, etc..
    What is the best approach to create an generic class that receives an string that represents an xml and load it?
    Is too ugly receives an String with the name of xml to load??
    Thanks for suggestions..

    This is my method that loads the xml configuration:
         private synchronized void loadPropriedades() throws FileException {
              if (propriedades != null) {
                   return;
              try {
                   DocumentBuilder db = JAXPFactory.getInstance().getFactory();
                   Document xml = db.parse(getClass().getResourceAsStream(
                             "/.xml"));
                   NodeList nodeListPrincipal = xml.getElementsByTagName("Config");
                   NamedNodeMap atributos = nodeListPrincipal.item(0).getAttributes();
                   Node nodeAtual = null;
                   propriedades = new HashMap();
                   for (int f = 0; f < atributos.getLength(); f++) {
                        nodeAtual = atributos.item(f);
                        propriedades.put(nodeAtual.getNodeName(), nodeAtual
                                  .getNodeValue());
              } catch (SAXException sae) {
                   Log.error("Erro na leitura do XML de configurações do sistema", se);
              } catch (ParserConfigurationException pace) {
                   Log.error("Erro ao traduzir XML de configurações do sistema", pce);
              } catch (IOException ioe) {
                   Log.error("Erro na abertura do XML de configurações do sistema",
                             ioe);
              } catch (Exception e) {
                   Log.error(e);
    My idea is transform the method above to something like private synchronized void loadPropriedades(String XmlReceived) <----------------------------------- To avoid create one class to each xml, make a class to load, but i dont know if receives a String with xml name is good...
    Understand?
    Thanks !

  • Ho can I print child from XML file

    I'm trying to print the child of one parent..it's not working I don't have no clue...bello is the code and the XML
    DocumentBuilderFactory aronXml = DocumentBuilderFactory.newInstance();
    DocumentBuilder aronText = aronXml.newDocumentBuilder();
    Document aronDoc = aronText.parse (new File("XML/"+"laPartieWord.xml"));
    NodeList tagSolution = aronDoc.getElementsByTagName("solution");
    /* HOW TO GET CHILD OF SOLUTION*/Here is the XML file
    <?xml version="1.0"?>
    <aaron1 lettres="DEORSU"
    xmlns="com.ingenioquebec.dyna01.dictionnaire"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="com.ingenioquebec.dyna01.dictionnaire laPartieWord.xsd">
         <solution>
              <mot3 mot="DOS"/>
              <mot3 mot="DOS"/>
              <mot4 mot="DUSF"/>
              <mot4 mot="DUVF"/>     
              <mot6 mot="NTISRO"/>     
         </solution>
         <dictionnaire>
              <mot3 mot="DES"/>
              <mot3 mot="DES"/>
              <mot4 mot="DECV"/>
              <mot4 mot="CLAY"/>
         </dictionnaire>
    </aaron1 >     
         

    did you try the Node.getChildNodes() method?

  • How to get child elements of element in xml?

    public class Test {
         public static void main(String[] args) {
              Document doc = null;
              System.out.println("!!!");
              try {
                   // TODO if path is 'c:' then make it 'c:/'
                   doc=DocumentBuilderFactory.newInstance().newDocumentBuilder().parse("test.xml");
              } catch (Exception e) {
                   System.out.println("exception");
              Element root = doc.getDocumentElement();
              NodeList dsList = root.getElementsByTagName("GenericDataSource");
              Element e = (Element)dsList.item(0);
             NodeList nl = e.getChildNodes();
             System.out.println(nl.getLength());
             Node n  = nl.item(0);
             Element ee = (Element)n;
    }i want to get child elements. but its throwing exception on typecasting. can u tell me why?

    thanks for the info.
    i got 2 solutions
    SOLUTION 1:
    public class Test {
         public static void main(String[] args) throws Exception {
              Document doc = null;
              System.out.println("!!!");
              try {
                   // TODO if path is 'c:' then make it 'c:/'
                   doc=DocumentBuilderFactory.newInstance().newDocumentBuilder().parse("test.xml");
              } catch (Exception e) {
                   System.out.println("exception");
              Element root = doc.getDocumentElement();
              NodeList dsList = root.getElementsByTagName("GenericDataSource");
              Element e = (Element)dsList.item(0);
             NodeList nl = e.getChildNodes();
             int count = 0;
             System.out.println(nl.getLength());
             for(int i=0;i<nl.getLength();i++){
                      Node n  = nl.item(i);
                     //System.out.println(n.getClass().getName()); 
                     //System.out.println((Element)n);
                     if(n instanceof Element){ // this checks for node type
                          count++;
                          System.out.println("Element "+(Element)n);
    SOLUTION 2: :
    XPath xpath  = XPathFactory.newInstance().newXPath();
             InputSource inputSource = new InputSource("test.xml");
             NodeList nodes = (NodeList) xpath.evaluate("//GenericDataSource/*", inputSource, XPathConstants.NODESET);
             System.out.println(nodes.getLength());
             System.out.println((Element)nodes.item(9));

  • To read xsl values of subsequent nodes in xml document

    Hi,
    I have a xml document which looks something like this
    <report>
    <prelist>
    <row>
    <field name="learning" value="Internet basics"/>
    </row>
    <row>
    <field name="learning" value="General Knowlege"/>
    </row>
    </prelist>
    <list>
    <row>
    <field name="learning" value="Internet basics"/>
    <field name="tool" value="xml"/>
    </row>
    <row>
    <field name="learning" value="Internet basics"/>
    <field name="tool" value="xmlxsl"/>
    </row>
    <row>
    <field name="learning" value="General Knowledge"/>
    <field name="tool" value="xmltool"/>
    </row>
    </list>
    </report>
    What i would like to do is
    I read the prelist structure and retrieve the value of "learning"
    For each value i retrieve i would like to read the list structure for similar values
    e .g in first iteration i get the value = "Internet Basics" from prelist node then from list node i would like tool node with value = "xml" and value="xmlxsl"
    Please let me know if this is possible and nay help would be appreciated..
    Thanks.

    I don't see how you go from the prelist to the list but I guess that doesn't matter.
    You can load the XML into a DOM document then use the Document method:
    getElementsByTagName
    public NodeList getElementsByTagName(String tagname)
    Returns a NodeList of all the Elements with a given tag name in the order in which they are encountered in a preorder traversal of the Document tree.
    Parameters:
    tagname - The name of the tag to match on. The special value "*" matches all tags. Returns:
    A new NodeList object containing all the matched Elements.

  • Simple XML parsing with DOM

    I have a XML file i need to parse. Can please someone give me a hint how to do this(please include code). Please note that im a new in XML and my DOM structure knowledge in limited(im confused from all the tutorials).
    XML code:
    <Vitals>
    <Hostname>sometest</Hostname>
    <IPAddr>sometest</IPAddr>
    <Kernel>sometest</Kernel>
    <Uptime>sometest</Uptime>
    <Users>sometest</Users>
    <LoadAvg>sometest</LoadAvg>
    </Vitals>
    <Network>
    <NetDevice>
    <Name>lo</Name>
    <RxBytes>10425010</RxBytes>
    <TxBytes>10425010</TxBytes>
    <Errors>0</Errors>
    <Drops>0</Drops>
    </NetDevice>
    <NetDevice>
    <Name>eth0</Name>
    <RxBytes>627976843</RxBytes>
    <TxBytes>2394415516</TxBytes>
    <Errors>271</Errors>
    <Drops>0</Drops>
    </NetDevice>
    </Network>
    So far ima at this step:
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    try {
    DocumentBuilder builder = factory.newDocumentBuilder();
    document = builder.parse( new File("NewFile.xml") );

    Just as simple text in console.
    Please give me the code.
    Is there any diference in document (DOM) if you create it with DFD or w/h ?
    So far i have this code, but it dosnt work for me(i get nothing as output:
    document = builder.parse( new File("NewFIle.xml") );
    NodeList list = document.getElementsByTagName("coffee");
    // Loop through the list.
    for (int k=0; k < list.getLength(); k++) {
    Node thisCoffeeNode = list.item(k);
    Node thisNameNode = thisCoffeeNode.getFirstChild();
    if (thisNameNode == null) continue;
    if (thisNameNode.getFirstChild() == null) continue;
    if (! (thisNameNode.getFirstChild() instanceof org.w3c.dom.Text)) continue;
    String data = thisNameNode.getFirstChild().getNodeValue();
    System.out.println(data);
    }

Maybe you are looking for

  • Limitation on number of presentations in iuXML page?

    Is there a limitation on the number of presentations that can be put into a iuXML page? When I click on the paging control for one of the crosstabs on the following page, I get an error in the browser stating "Error on page - Invalid Syntax" then it

  • In CP5 - problem with the 'Paste as Background' option

    Hi, Since I have started working with CP5 I am having issues with the 'Paste as Background' option. After I work with CP5, and use the option few times it disappears from the menu although I have an image copied to my clipboard. After I close Captiva

  • Teradata Source SQL Server where clause In SSIS

    Hi All,, I want pull the data from Teradata to SQLServer .But Teradata source query in where clause around 200 productcodes manually. Instead of that one I want pass sqlserver table dynamically . creating  one temp table in ssis for sqlserver data an

  • Compressor settings for good font quality in H264?

    I've tried a lot but when I stream a HD movie with compressor, I got not a sharp and nice qualty of the text on my edit project. I stream in H264 11000kbps in 1280 x 720 (second pass streaming). When I see the text on the movie trailers on the Apple

  • DDL to execute ?

    Hi oracle 10.2.0.1.0 I have created a view on table as create table try_table ( sno number); create or replace view try_table_vw as select * from try_table;When I alter the table and select/ desc the view then new coluymn is nt reflected until I recr