Adding ?xml to DOM

How do you add <?xml version="1.0" ?> to a DOM document? I can add nodes, but can;t seem to add this one.
Thanks!

You do not add it directly, but you instead instruct the transformer whether it should be included:
Transformer transformer = null;  // initialize in a spiffy way
transformer.setOutputProperty(OutputKeys.STANDALONE, "yes");
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");- Saish

Similar Messages

  • Parsing an XML using DOM parser in Java in Recursive fashion

    I need to parse an XML using DOM parser in Java. New tags can be added to the XML in future. Code should be written in such a way that even with new tags added there should not be any code change. I felt that parsing the XML recursively can solve this problem. Can any one please share sample Java code that parses XML recursively. Thanks in Advance.

    Actually, if you are planning to use DOM then you will be doing that task after you parse the data. But anyway, have you read any tutorials or books about how to process XML in Java? If not, my suggestion would be to start by doing that. You cannot learn that by fishing on forums. Try this one for example:
    http://www.cafeconleche.org/books/xmljava/chapters/index.html

  • Problem in parsing XML using DOM Parser.

    Hi,
    I am parsing an XML using DOM Parser.
    When i try to get attributes of a node, i dont get in the order it is written. For Eg. This the node:
    <Level0 label="News" link="/website/ing_news.nsf/ViewNewsForm?OpenForm&All" level="202" uid="COGN-4MNMT3" parentid="aaaa">
    When i try to print the attribute values i should get in the order:
    News, /website/ing_news.nsf/ViewNewsForm?OpenForm&All, 202, COGN-4MNMT3, aaaa
    BUT I AM GETTING IN THE ORDER:
    News, 202, /website/ing_news.nsf/ViewNewsForm?OpenForm&All, aaaa, COGN-4MNMT3
    Is there any way to sort this problem out?
    Thanks and Regards,
    Ashok

    Hi Guys,
    Thanks a lot for your replies.
    But i want to keep all the values as attributes only.
    the XML file is as shown below:
    <Menu>
    <Level0 label="News" link="/website/ing_news.nsf/ViewNewsForm?OpenForm&All" level="202" uid="COGN-4MNMT3" parentid="aaaa" children="3">
         <Level1 label="ING News" link="" level="1" uid="COGN-4MNN89" parentid="COGN-4MNMT3" children="3" >
              <Level2 label="All ING News" link="/website/ing_news.nsf/ViewNewsForm?OpenForm&All" level="2" uid="INGD-4MVTK2" parentid="COGN-4MNN89" children="0">
              </Level2>
    </Level1>
    </Level0>
    The code i was using to get attributes is:
    String strElementName = new String(node.getNodeName());
         // System.out.println("strElementName:"+node.getNodeName());
    NamedNodeMap attrs = node.getAttributes();
    if (attrs != null) {
    int iLength = attrs.getLength();
    for (int i = 0; i < iLength; i++) {
    String strAttributes = (String) attrs.item(i).getNodeName();
    String strValues = (String) attrs.item(i).getNodeValue();
    Also is it not possible to Enforce the order using some Schema/DTD in this case?
    TIA
    Ashok

  • Convertion of flat file to XML using DOM

    Hi!
    I need help for convert a flat file to XML using DOM and by taking the validation of a specified DTD. Can any body help me in this regard.
    Bye,
    lat

    first you have to decide how the flat file will map to xml. Will you use attributes or pcdata for your fields, or both? Will there be a hierarchy, or will it be mostly flat?
    Once decided, you'd probably just use a BufferedReader to read the lines one at a time, and generate Dom nodes as appropriate, and stick them in the tree.

  • Rounding of decimal values into XML using DOM

    I want to roundoff 10.456 to 10.4(while generating the xml) using DOM.
    Please let me know how to handle this?
    Thanks in advance

    read the java.lang.Math API
    there are rounding functions there
    and next time please just use a search engine

  • Xml to dom and vice versa

    Hello
    I want to modify my current program in order to parse the created dom to a new xml file
    Can anyone explain how / help me to do that?
    Thanks in advance !
    //the code below parse an xml to dom
    import java.io.File;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    import java.util.*;
    public class XMLReader {
            public static void main(String argv[]) {
                    try {
                            File file = new File("personnel.xml");
                            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                            DocumentBuilder db = dbf.newDocumentBuilder();
                            Document doc = db.parse(file);
                            doc.getDocumentElement().normalize();
                            System.out.println("Personnel" + doc.getDocumentElement().getNodeName());
                            NodeList nodeLst = doc.getElementsByTagName("person id");
                            System.out.println("Information of all employees");
                            ArrayList<Employee> empList = new ArrayList<Employee> ();
                            for (int s = 0; s < nodeLst.getLength(); s++) {
                                Employee emp = new Employee ();
                                    Node fstNode = nodeLst.item(s);
                                    if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
                                            Element fstElmnt = (Element) fstNode;
                                            NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("firstname");
                                            Element fstNmElmnt = (Element) fstNmElmntLst.item(0);
                                            NodeList fstNm = fstNmElmnt.getChildNodes();
                                            System.out.println("First Name : " + ((Node) fstNm.item(0)).getNodeValue());
                                            emp.firstName = ((Node) fstNm.item(0)).getNodeValue();
                                            NodeList lstNmElmntLst = fstElmnt.getElementsByTagName("lastname");
                                            Element lstNmElmnt = (Element) lstNmElmntLst.item(0);
                                            NodeList lstNm = lstNmElmnt.getChildNodes();
                                            System.out.println("Last Name : " + ((Node) lstNm.item(0)).getNodeValue());
                                            emp.lastName = ((Node) fstNm.item(0)).getNodeValue();
                    } catch (Exception e) {
                            e.printStackTrace();
    class Employee {
        public String person_id;
        public String firstName;
        public String lastName;
        public Address address;
        public String phone;
    class Address {
        public String street;
        public String house_number;
        public String town;
        public String zip;
    }

    Oops sorry i just want to create a method which saves the created dom document as an xml file.
    Thanks in advance !

  • Adding XML Attriubutes to Nodes

    Hello,
    I'm working on a project that requires parsing of messages between server and client programs and we're using XML as the language.
    The server is programmed in C# and the client in Java ..
    I need something like this:
    <ROOM>
    <TYPE message="CREATE">
    // A create type message goes in here
    </TYPE>
    </ROOM>
    The following is the method that actually creates the message (located in the client) ...
    public void CreateRoomOperationMessage (String toLocation, String roomName, String messageOperation) {
            // The create room operation message is a method which creates the create/kill messages
            try {
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                DocumentBuilder builder = factory.newDocumentBuilder();
                DOMImplementation impl = builder.getDOMImplementation();
                Document doc = impl.createDocument(null, toLocation, null);
                Node rootElement = doc.getDocumentElement();
                Node roomNode = doc.createElement(ROOM);
                rootElement.appendChild(roomNode);
                Node typeNode = doc.createElement(TYPE);
                roomNode.appendChild(typeNode);
                //Element typeElement = doc.getElementsByTagName(TYPE);
                //typeElement.setAttribute("MESSAGE", messageOperation);
                // PROBLEM ... NEED TO FIGURE OUT HOW TO INSERT AN ELEMENT INTO THE TREE?
                Text typeText = doc.createTextNode(messageOperation);
                typeNode.appendChild(typeText);
                Node roomNameNode = doc.createElement(ROOMNAME);
                roomNode.appendChild(roomNameNode);
                Text roomNameText = doc.createTextNode(roomName);
                roomNameNode.appendChild(roomNameText);
                TransformerFactory xformFactory = TransformerFactory.newInstance();
                Transformer idTransform = xformFactory.newTransformer();
                Source input = new DOMSource(doc);
                Writer txtWriter = new StringWriter();
                Result output = new StreamResult(txtWriter);
                idTransform.transform(input, output);
                setXmlMessage(txtWriter.toString());
            } catch (FactoryConfigurationError e) {
                System.err.println("ROOMMESSAGEFACTORY: Could not locate a JAXP factory class");
            } catch (ParserConfigurationException e) {
                System.err.println("ROOMMESSAGEFACTORY: Could not locate a JAXP DocumentBuilder class");
            } catch (DOMException e) {
                System.err.println("ROOMMESSAGEFACTORY: DOM Exception");
                System.err.println(e);
            } catch (TransformerConfigurationException e) {
                System.err.println("ROOMMESSAGEFACTORY: Input to Output transformation error!");
                System.err.println(e);
            } catch (TransformerException e) {
                System.err.println("ROOMMESSAGEFACTORY: Transformer Exception");
                System.err.println(e);
        }I just don't see any way of taking a node and setting/adding an attribute ...
    eg .. Node typeNode = doc.createElement(TYPE);
    roomNode.appendChild(typeNode);
    typeNode.setAttribute("message", messageOperation); // This is the pseudocode

    The return value of createElement() is an Element, and Element has a setAttribute method. Just don't implicitly upcast to Node and your pseudocode is correct.Element  typeNode = doc.createElement(TYPE);
    roomNode.appendChild(typeNode);
    typeNode.setAttribute("message", messageOperation);Pete

  • Reimporting exported XML using DOM

    Hi,
    I'm trying to set up an import/export for a data structure, 'SimpleNode' created by a JavaCC parser for classical propositional logic.
    SimpleNode implements Node, and have the following attributes
    protected SimpleNode parent;
    protected SimpleNode[] children;
    protected int id;
    protected LogicParser parser;
    protected String label;
    ...So nothing too special there.
    A simple representation of the sentence
    a OR (b AND c) IMPLIES NOT(D)
    "a | (b & c) => !d"
    Is represented as a tree with in the following manner
    Root
    Imp
      Or
       Atom a
       And
        Atom b
        Atom c
      Not
       Atom dWhich is all fine.
    I've written something to export to an XML structure which gives the following output for the above sentence
    <IMPLIES>
      <NOT>
        <TRUE/>
      </NOT>
      <IMPLIES>
        <OR>
          <ATOM>a</ATOM>
          <ATOM>b</ATOM>
        </OR>
        <NOT>
          <ATOM>c</ATOM>
        </NOT>
      </IMPLIES>
    </IMPLIES>Which again, seems fine.
    The problem is then when I'm trying to reimport the XML and create a SimpleNode from it.
    Using the following code
         public static void main(String[] args) {
              // if (args.length <= 0) {
              // System.out.println("Usage: java DOMCommentReader URL");
              // return;
              String url = "propLogic.xml";
              try {
                   DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                   DocumentBuilder parser = factory.newDocumentBuilder();
                   // Check for the traversal module
                   DOMImplementation impl = parser.getDOMImplementation();
                   if (!impl.hasFeature("traversal", "2.0")) {
                        System.out.println("A DOM implementation that supports traversal is required.");
                        return;
                   // Read the document
                   Document doc = parser.parse(url);
                   // Create the TreeWalker
                   DocumentTraversal traversable = (DocumentTraversal) doc;
                   // Taken from
                   // http://www.oreilly.com/catalog/jenut2/chapter/ch19.html
                   NodeFilter filter = new NodeFilter() {
                        public short acceptNode(Node n) {
                             if (n.getNodeType() == Node.TEXT_NODE) {
                                  // Use trim() to strip off leading and trailing space.
                                  // If nothing is left, then reject the node
                                  if (((Text) n).getData().trim().length() == 0)
                                       return NodeFilter.FILTER_REJECT;
                                  // if (n.getParentNode().getNodeName() != "ATOM")
                                  // return NodeFilter.FILTER_REJECT;
                             return NodeFilter.FILTER_ACCEPT;
                   int whatToShow = (NodeFilter.SHOW_ELEMENT + NodeFilter.SHOW_TEXT);
                   TreeWalker iterator = traversable.createTreeWalker(doc, whatToShow, filter, true);
                   printElements(iterator, 0);
              } catch (SAXException e) {
                   System.out.println(e);
                   System.out.println(url + " is not well-formed.");
              } catch (IOException e) {
                   System.out.println("Due to an IOException, the parser could not check " + url);
              } catch (FactoryConfigurationError e) {
                   System.out.println("Could not locate a factory class");
              } catch (ParserConfigurationException e) {
                   System.out.println("Could not locate a JAXP parser");
         public static void printElements(TreeWalker iterator, int depth) {
              Node n = iterator.getCurrentNode();
              n.normalize();
              String indent = new String();
              for (int i = 0; i < depth; i++) {
                   indent += "  ";
              depth++;
              System.out.print(indent + n.getNodeName() + " " + n.getNodeValue());
    //          if (n.getParentNode() != null)
    //               System.out.print(" (parent is " + n.getParentNode().getNodeName() + ")");
              System.out.println();
              for (Node child = iterator.firstChild(); child != null; child = iterator.nextSibling()) {
                   printElements(iterator, depth);
              iterator.setCurrentNode(n);
         }I can get a correct looking representation of the structure
    #document null
      IMPLIES null
        NOT null
          TRUE null
        IMPLIES null
          OR null
            ATOM null
              #text a
            ATOM null
              #text b
          NOT null
            ATOM null
              #text cBut I'm having trouble using the Iterator to create SimpleNodes from the Nodes
    All a SimpleNode needs is a type (an integer representing whether the operator is AND, OR, NOT, IMPLIES etc)
    and a label, which can be null or in the case of an ATOM will have the atom name, "a", "b", "c" etc.
    A SimpleNode is easily created with the constructor
    SimpleNode foo = new SimpleNode(type);
    foo.setLabel("a");
    and adding a child by
    foo.jjtAddChild(SimpleNode n, int i)
    where i is the number of the child.
    Hopefully I've not rambled too much and it makes sense.
    If anyone can give me any pointers or some code/pseudocode to pick through then it'd be much appreciated.
    Duncan

    No bother, tweaked the printElements to fix.

  • Update XML using DOM or RandomAccessFile

    Morning,
    One of my server apps stores client resource data in an XML file. Quite often, a process will want to update, add, or remove nodes based upon requirement. Is it less efficient to load the entire XML document into the DOM and modify it or just use RandomAccessFile to search for specific byte patterns and perform my modifications?
    Or, does it really matter? Using the DOM would be more in keeping with its intended purpose vs the more direct byte by byte approach.
    Thank you,
    Stig.

    Well, if all of your modifications are guaranteed to preserve the length of every node in the document, then I suppose you could use a RandomAccessFile. But if somebody someday is going to ask for a text node to be changed from "Mary" to "Maria" then a RandomAccessFile would be just a huge pain. You would have to move everything after that node one char to the right.
    I'm betting your requirements fail that length-preservation test. Especially since you mentioned adding and removing nodes. Just use the DOM already.

  • Creating XML String DOM

    Hi ppl,
    I need some help with DOM Object. I have a xml file which I parse with dom and when I do some changes in dom object like adding new element or changing the values of existing object and now when I try to transorm the dom object back to a xml string. It puts everything in one line. for example say my xml file is like:-
    <student>
        <name>john</name>
        <result>pass</result>
    </student>Now when I add new element <address> to it , change value of existing element and try to get xml string i get something like this
    <student><name>smith</name><address>412Miam</address><result>pass</result></student>
    Whole xml in one or two lines, instead of proper xml with one element and its value in one line.
    Any ideas how to achieve this?

    Ddosot,
    Thank you very much. I was looking for this from long time.
    Honeslty I have searched news group many times but couldnt get an answer, may be my search words were not correct.
    you could have saved all this writing by running a
    little search on this forum, as this questions is
    asked once per day.
    anyway, here is your answer:
    transformer.setOutputProperty(OutputKeys.INDENT,
    "yes");
    transformer.setOutputProperty("{http://xml.apache.org/x
    lt}indent-amount", "1");

  • XML : Transform DOM Tree to XML String in an applet since the JRE 1.4.2_05

    Hello,
    I build a DOM tree in my applet.
    Then I transform it to XML String.
    But since the JRE 1.4.2_05 it doesn't work.
    These lines failed because these variables became final:
    org.apache.xalan.serialize.CharInfo.XML_ENTITIES_RESOURCE = getClass().getResource("XMLEntities.res").toString();
    org.apache.xalan.processor.TransformerFactoryImpl.XSLT_PROPERTIES = getClass().getResource("XSLTInfo.properties").toString();The rest of the code :
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = domFactory.newDocumentBuilder();
    Document domXML = builder.newDocument();
    // I build my DOM Tree
    StringWriter xmlResult = new StringWriter();
    Source source = new DOMSource(domXML);
    Result result = new StreamResult(xmlResult);
    Transformer xformer = TransformerFactory.newInstance().newTransformer();
    xformer.setOutputProperty(javax.xml.transform.OutputKeys.INDENT,"yes");
    xformer.transform(source,result);Is there any other way to get an XML String from a DOM tree in an applet ?
    I'm so disappointed to note this big problem.

    Does anyone have an idea why I get this error message when try to use transform in an applet?
    Thanks...
    java.lang.ExceptionInInitializerError
         at java.lang.Class.forName0(Native Method)
         at java.lang.Class.forName(Unknown Source)
         at org.apache.xalan.serialize.SerializerFactory.getSerializer(Unknown Source)
         at org.apache.xalan.transformer.TransformerIdentityImpl.createResultContentHandler(Unknown Source)
         at org.apache.xalan.transformer.TransformerIdentityImpl.transform(Unknown Source)
         at matrix.CreateMtrx.SaveDoc(CreateMtrx.java:434)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
         at java.lang.reflect.Method.invoke(Unknown Source)
         at thinlet.Thinlet.invokeImpl(Unknown Source)
         at thinlet.Thinlet.invoke(Unknown Source)
         at thinlet.Thinlet.handleMouseEvent(Unknown Source)
         at thinlet.Thinlet.processEvent(Unknown Source)
         at java.awt.Component.dispatchEventImpl(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)
    Caused by: java.lang.RuntimeException: The resource [ XMLEntities.res ] could not load: java.net.MalformedURLException: no protocol: XMLEntities.res
    XMLEntities.res      java.net.MalformedURLException: no protocol: XMLEntities.res
         at org.apache.xalan.serialize.CharInfo.<init>(Unknown Source)
         at org.apache.xalan.serialize.SerializerToXML.<clinit>(Unknown Source)
         ... 28 more

  • Problem in the Parsing (XML to DOM)

    Hi all , In our scenario we are trying to create a DOM tree from a XML file  but we are getting the error in the following statement 
    l_rc = if_iparser->parse( ).
    when we track the error using
      i = l_error->get_line( ).           (result 0)
      i = l_error->get_column( ).     (result 2017)
      str = l_error->get_reason( ).   (Expected '<' or '/>' tag)
    but strange thing is we can open the file using Stylus studio/ Altova / IE ..so may the problem is not in the XML file ....Has anybody faced the problem before ??
    Kind regarrds
    Goutam

    Data error

  • Parsing xml using DOM parser in java

    hi there!!!
    i don have much idea about parsing xml.. i have an xml file which consists of details regarding indentation and spacing standards of C lang.. i need to read the file using DOM parser in java n store each of the attributes n elements in some data structure in java..
    need help as soon as possible!!!

    DOM is the easiest way to parse XML document, google for JDOM example it is very easy to implement.
    you need to know what is attribute, what is text content and what is Value in XML then easily you can parse your document with dom (watch for space[text#] in your XML document when you parse it).
    you get root node then nodelist of childs for root then go further inside, it is easy believe me.

  • Remove element from xml using dom.

    i want to remove an element from an xml file using dom.
    i remove the element but the whole content of the file is also deleted.
    how can i rewrite the file.

    vij_ay wrote:
    subject :Remove element from xml,but if empty element in input file then output should be <tag></tag>, not like <tag.xml/>I assume you mean <tag/> but why do you want this? Any application that will not accept this valid XML construct is flawed and a bug report should be raised against it.

  • Adding org.w3c.dom.Node

    Hi,
    can someone please tell me if it is posible do read a org.w3c.dom.Node from one XML file, and than add it to another? Or is there a way to copy one org.w3c.dom.Node to another XML?
    Thanx,
    Alan.

    Refer to
    http://javaalmanac.com/egs/org.w3c.dom/CloneSubtree2.html

Maybe you are looking for

  • Problems with icons in System Pref

    Look at my system pref. http://www.stickyspy.com/misc/controlp.jpg The "Energy" icon has somehow changed. How do I can back the original icon? Please help.

  • Opening MS-Office files

    Hi, I installed MS Office 2004 on my iMac (intel). But now, when I open any Office file (.doc, .xls, ...) by double-clickin on an icon, they are associated with a "trial" version of MS Office. How can I change it, so that files are opened with the "r

  • Applicant number creation

    Hello, I created action called 'ZO' for applicant in 'SPRO'  transaction which generates applicant number. After applicant creation I got IT 4000 but didn't get IT 4003, without it I can not hire an employee. So I am not able to find configuration to

  • M.B.P not requesting my password when starts up.

    For some reason everytime I turn my computer on it gives full access to all of my imformation, it doesn't ask for the password I try changing it in system preferences/ accounts/ Login Options.. but nothing still doesn't work any ideas on how to fix t

  • Error in running Payroll

    No entry in Table T510J for key 9901 M240 for time 1.1.2007