Unparsing a DOM tree and write XML to file

Hi,
I have created a DOM tree from scratch and would like to unparse the DOM tree and write the XML to a file, but how do I do that?
Does anybody got code examples that do this?
All help are very appreciated!
/Daniel

Thank you very much for the hint! Unfortunaly I still got problem to get it work though.
I made a little piece of test code to try it but during the execution of the "Transformer.transform(source,result)" method I gets an "org.w3c.dom.DOMException".
Does anybody see what that problem might be cause of by exmining the code below?
I also would like to know how to specify the location where I would like to print out the XML file.
Here is my little piece of test code:
try{
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFadctory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
doc.appendChild(doc.createElement("topLevel"));
Element elm = doc.getDocumentElement();
elm = (Element)elm.appendChild(doc.createElement("PersonData"));
elm = (Element)elm.appendChild(doc.createElement("Name"));
elm.setAttribute("Firstname","D");
elm.setAttribute("Lastname", "D");
DOMResult result = new DOMResult(doc);
DOMSource source = new DOMSource(doc);
TransformerFactory transformerFactory = TansformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.transform(source,result);
}catch(ParserConfigurationException e) {
}catch(IOException e) {
}catch(TransformerException te) {

Similar Messages

  • How to Read and Write .XML datas   (HELP Plz...)

    hai everybody
    how to read and write xml datas... plz give clean and simple example..
    bcoz me want to produce such type of module...
    if any one help me .. thats the only way me laid in software ladder
    plz....
    thank u in advance

    thank u for giving idiot..
    but before posting i search in google also..
    but i cant get what me expect..
    thus i posted...
    then who is ................?
    sorry javacoder01
    // plz help me
    Message was edited by:
    drvijayy2k2

  • Tree based on XML DB files

    Has someone ever tried to build a tree based on XML DB files?
    Regards,
    Learco

    Hello,
    Yeah I've done that before, I basically was getting XML exports and was running them against one of 3 XSLT's , users choice , and one was a tree. I'll dig up the code.
    Or are you talking about building a tree based on all the files in XMLDB to navigate around them, I have a start on that I can give you as well, never finished it though.
    Regards,
    Carl
    blog : http://carlback.blogspot.com/
    apex examples : http://apex.oracle.com/pls/otn/f?p=11933:5

  • How to read the and Write the PDF file give me the solution

    Hi all,
    How to read the and Write the PDF file give me the solution
    My coding is
    import java.io.File;
    import com.asprise.util.pdf.PDFImageWriter;
    import com.asprise.util.pdf.PDFReader;
    import java.io.*;
    import java.io.FileOutputStream;
    public class example {
    // public example() {
         public static void main(String a[])
              try
              PDFReader reader = new PDFReader(new File("C:\\AsprisePDF-DevGuide.pdf"));
                   reader.open(); // open the file.
                   int pages = reader.getNumberOfPages();
                   for(int i=0; i < pages; i++) {
                   String text = reader.extractTextFromPage(i);
                   System.out.println("Page " + i + ": " + text);
    // perform other operations on pages.
    PDFImageWriter writer = new PDFImageWriter(new FileOutputStream("c:\\new11.pdf"));
                   writer.open();
                   writer.addImage("C:\\sam.doc");
                   writer.close();
                   System.out.println("DONE.");
    reader.close();
              catch(Exception e){System.out.println("error:"+e);
              e.printStackTrace();
    I get the pdf content then it returns the string value but ther is no option to write the string to PDF, and we only add a image file to PDF,but i want to know how to wrote the string value to PDF file,
    Please give response immtly
    i am waiting for your reply.
    thanks,
    Suresh.G

    I have some question flow
    How library to use this code.
    I try runing but have not libary.
    Please send me it'library
    Thank you very much!

  • Read and write a .CSV file contains cirillic characters issue

    Hi guys,
    I am a developer of a web application project which uses Oracle Fusion Middleware technologies. We use JDeveloper 11.1.1.4.0 as development IDE.
    I have a requirement to get a .csv file from WLS to application running machine. I used a downloadActinLinsener in front end .jspx in order to do that.
    I use OpenCSV library to read and write .csv files.
    Here is my code for read and write the .csv file,
    public void dwdFile(FacesContext facesContext, OutputStream out) {
    System.out.println("started");
    String [] nextLine;
    try {
    FileInputStream fstream1 = new FileInputStream("Downloads/filetoberead.CSV");
    DataInputStream in = new DataInputStream(fstream1);
    BufferedReader br = new BufferedReader(new InputStreamReader(in,"UTF-8"));
    CSVReader reader = new CSVReader(br,'\n');
    //CSVReader reader = new CSVReader(new FileReader("Downloads/ACTIVITY_LOG_22-JAN-13.csv"),'\n');
    List<String> list=new ArrayList();
    while ((nextLine = reader.readNext()) != null) {
    if(nextLine !=null){
    for(String s:nextLine){
    list.add(s);
    System.out.println("list size ; "+list.size());
    OutputStreamWriter w = new OutputStreamWriter(out, "UTF-8");
    CSVWriter writer = new CSVWriter(w, ',','\u0000');
    for(int i=0;i<list.size();i++){
    System.out.println("list items"+list.get(i));
    String[] entries = list.get(i).split(",");
    writer.writeNext(entries);
    //System.out.println("list items : "+list.get(i));
    writer.close();
    } catch (IOException e) {
    e.printStackTrace();
    say the filetoberead.CSV contains following data,
    0,22012013,E,E,ASG,,O-0000,O,0000,100
    1,111211,LI,0,TABO,B,M002500003593,,,К /БЭ60072715/,КАРТЕНБАЙ
    2,07,Balance Free,3
    1,383708,LI,0,BDSC,B,НЭ63041374,,,Т /НЭ63041374/,ОТГОНБААТАР
    2,07,Balance Free,161
    It reads and writes the numbers and english characters correct. All cirillic characters it prints "?" as follows,
    0,22012013,E,E,ASG,,O-0000,O,0000,100
    1,111211,LI,0,TABO,B,M002500003593,,,? /??60072715/,?????????
    2,07,Balance Free,3
    1,383708,LI,0,BDSC,B,??63041374,,,? /??63041374/,???????????
    2,07,Balance Free,161
    can somone please help me to resolve this problem?
    Regards !
    Sameera

    Are you sure that the input file (e.g. "Downloads/filetoberead.CSV") is in UTF-8 character set? You can also check it using some text editor having a view in hex mode. If each Cyrillic character in your input file occupies a single byte (instead of two), then the file is not in UTF-8. Most probably it is in Cyrillic for Windows (CP1251).
    If this is the case, you should modify the line
    BufferedReader br = new BufferedReader(new InputStreamReader(in,"UTF-8"));toBufferedReader br = new BufferedReader(new InputStreamReader(in,"windows-1251"));Dimitar

  • How to read from one file and write into another file?

    Hi,
    I am trying to read a File and write into another file.This is the code that i am using.But what happens is last line is only getting written..How to resolve this.the code is as follows,
    public String get() {
         FileReader fr;
         try {
              fr = new FileReader(f);
              String str;
              BufferedReader br = new BufferedReader(fr);
              try {
                   while((str= br.readLine())!=null){
                   generate=str;     
              } catch (IOException e1) {
                   e1.printStackTrace();
              } }catch (FileNotFoundException e) {
                   e.printStackTrace();
         return generate;
    where generate is a string declared globally.
    how to go about it?
    Thanks for your reply in advance

    If you want to copy files as fast as possible, without processing them (as the DOS "copy" or the Unix "cp" command), you can try the java.nio.channels package.
    import java.nio.*;
    import java.nio.channels.*;
    import java.io.*;
    import java.util.*;
    import java.text.*;
    class Kopy {
         * @param args [0] = source filename
         *        args [1] = destination filename
        public static void main(String[] args) throws Exception {
            if (args.length != 2) {
                System.err.println ("Syntax: java -cp . Kopy source destination");
                System.exit(1);
            File in = new File(args[0]);
            long fileLength = in.length();
            long t = System.currentTimeMillis();
            FileInputStream fis = new FileInputStream (in);
            FileOutputStream fos = new FileOutputStream (args[1]);
            FileChannel fci = fis.getChannel();
            FileChannel fco = fos.getChannel();
            fco.transferFrom(fci, 0, fileLength);
            fis.close();
            fos.close();
            t = System.currentTimeMillis() - t;
            NumberFormat nf = new DecimalFormat("#,##0.00");
            System.out.print (nf.format(fileLength/1024.0) + "kB copied");
            if (t > 0) {
                System.out.println (" in " + t + "ms: " + nf.format(fileLength / 1.024 / t) + " kB/s");
    }

  • How can i write the DOM tree to the XML File?

    Asslamo ala mn etb3a Alhoda.
    My problem priefly is that i can't write the DOM tree to XML file.
    I write following code to give the user the ability to input the name of data base which he want to create.
    If i wrote DB name,its atrributes and its values succefully to XML file ,then i'll read it succefully to RAM.
    It'll be simple DBMS.
    ***My code***
    import javax.swing.*;
    import javax.xml.parsers.*;
    import org.w3c.dom.Document;
    import org.w3c.dom.DOMException;
    import org.w3c.dom.Element;
    public class Main {
         * @param args
    public static void main(String[] args) {
         // TODO Auto-generated method stub     
         String DBname;
    DBname=JOptionPane.showInputDialog("Enter Your Data Base Name");
    OPerations O=new OPerations();
         O.creatDB(DBname);
    class OPerations {
    public void creatDB(String name){
         //get an empty Document
         DocumentBuilderFactory f; f=DocumentBuilderFactory.newInstance();
         try {
              builder = f.newDocumentBuilder();
              Document doc= builder.newDocument();
         //Build tree DOM With the root Node
              Element root=doc.createElement(name);
         //add the root element to thevdocument
              doc.appendChild(root);
    catch (ParserConfigurationException e) {
         // TODO Auto-generated catch block
              e.printStackTrace();
    }

    Do an identity transformation to output it:TransformerFactory tf = TransformerFactory.newInstance();
    Transformer tr = tf.newTransformer();
    tr.transform(new DOMSource(doc), new StreamResult(new FileOutputStream(new File(filename))));(typed without syntax check)

  • Loop through xml, update field values and write to a file

    I have the following xml file:
    <candy>
    <product><column name="Data">123</column>
    <column name="Date">2002-1-1</column>
    </product>
    <product><column name="Data">456</column>
    <column name="Date">2002-1-1</column>
    </product></candy>
    I need to update column name="Date" from its current values to a new value and then write it to a file in java. I know the steps is to build a dom tree - xml parser-xpath ect. Can anyone provide some working examples or links? I did some search on web, but could not find any examples that meet my requirements.
    Thank you for your input.

    Here's a starting point for you:
    http://java.sun.com/webservices/docs/1.0/tutorial/doc/JAXPDOM3.html

  • Anyone have example to read and write XML to/from file

    I am writing a swing utility and need to save and read data in XML. I have looked around google, but the examples are just confusing me.
    Jonathan

    Do these xml docs have dtd's? And specific DOM implementation needs or just a custom xml?
    I have some examples in http://cvs.sourceforge.net/viewcvs.py/mathml-x/mathml-x/src/com/neuralworks/physics/Academy.java?view=markup
    follow openMenuItemActionPerformed and openFEMMLDocument(String filePath). Look for DocumentBuilder
                DocumentBuilderFactory factory =
                DocumentBuilderFactory.newInstance();
    /*            factory.setAttribute("element.factory",
                                     ELEMENT_FACTORY);
                factory.setAttribute("attribute.factory",
                                     ATTR_FACTORY);
                DocumentBuilder builder = factory.newDocumentBuilder();
                //builder.setEntityResolver(new X3DEntityResolver());
                //builder.setErrorHandler(new X3DErrorHandler());
                femDoc = findXMLFile(builder, filePath);
                org.w3c.dom.Element docElement=femDoc.getDocumentElement();
                javax.swing.tree.DefaultMutableTreeNode dmtn=new javax.swing.tree.DefaultMutableTreeNode("FEMML");
                javax.swing.tree.DefaultMutableTreeNode svgChild=new javax.swing.tree.DefaultMutableTreeNode(docElement.getNodeName());
                //System.out.println(svgDocument.getTitle()+" nv "+svgSVGElement.getNodeValue());
                //recurseDOM2TreeNodes(svgChild, docElement.getChildNodes());
                dmtn.add(svgChild);
                JTree tree=new JTree(new javax.swing.tree.DefaultTreeModel(dmtn));
                tree.setRootVisible(true);
                tree.setShowsRootHandles(true);
                tree.setEditable(true);
                //try
                    //X3DTreeAdapter x3dTreeAdapter=new X3DTreeAdapter(x3dDTDParser.parse());
                    //org.web3d.x3d.dom.swing.DOMTreeCellEditor domTreeCellEditor=new org.web3d.x3d.dom.swing.DOMTreeCellEditor();
                    //tree.setCellEditor(domTreeCellEditor);
                    //org.web3d.x3d.dom.swing.DOMTreeCellRenderer domTreeCellRenderer=new org.web3d.x3d.dom.swing.DOMTreeCellRenderer();
                    //domTreeCellRenderer.addMouseListener(x3dTreeAdapter);
                    //domTreeCellRenderer.addMouseMotionListener(x3dTreeAdapter);
                    //tree.setCellRenderer(domTreeCellRenderer);
                    //tree.addMouseListener(x3dTreeAdapter);
                    //tree.addMouseMotionListener(x3dTreeAdapter);
                    academicSplitPane.setLeftComponent(new JScrollPane(tree));Lot of commented out stuff I need to clean up. There are other examples of opening specific xml docs that have special DOM implementations; svg and mathml for example.
    For saving I use xslt with an identity transform to go from an in memory DOM source to an xml document on disk.
    Follow the saveAs(String filePath) method and the identity.xsl is http://cvs.sourceforge.net/viewcvs.py/mathml-x/mathml-x/stylesheets/identity.xsl?rev=1.2&view=markup

  • How to read  and write XML in java

    I have a code that reads a large XML file, splits it into smaller files, filters and then writes it into a new XML file. My problem is that I had coded the input file name into the code, so that only the specified file can be read. How can I rewrite my code to be able to take any input xml and perform the same operation? Here's a portion of my code below:
                            File file = new File("c:\\APAdjustmentJVDoc_FINAL.xml");
                        output = new BufferedWriter(new FileWriter(file));
                        for (int i = 1; i < 79; i++) {
                             fIStream = new FileInputStream("c:\\APAdjustmentJVDoc_new" + i + ".xml");
                             loRead = new InputStreamReader(fIStream);
                             doc = XMLUtil.transformToNode(loRead, false);
                             System.out.println("Reading from file " + "c:\\APAdjustmentJVDoc_new" + i + ".xml");
                             writeFile(doc, docIdList, output);
                             fIStream.close();
                             loRead.close();
                        System.out.println("Output file complete");
                   } catch (Exception e) {
                        e.printStackTrace();
                   } finally {
                        if (output != null) {
                             output.close();
                        if (fIStream != null) {
                             fIStream.close();
              } catch (Exception e) {
                   e.printStackTrace();
                 

    You need to pass your filename String as a parameter to your functionality. It depends how you're currently set up though. We can't really see the top of your call so it's difficult to determine what you are calling and we don't really know from where you're calling either.
    If you're running standalone, then on launch of the application, you can feed in a file name as an argument that you can read in in String args[] in the main function and pass down to your XML splitter.
    If you're a method in a class that's part of a bigger pile, you can feed the file name as a String to the method from wherever you call from if it makes sense architecturally.
    You might also want to pass down a File object if that makes sense in your current code (i.e. if you're using your file for other purposes prior to the split, to avoid recreating closing/opening for no reason).
    Depends what you're trying to do. If I put together a piece like this, I would probably create an <yourcurrentrootpackage>.xml.splitter package.
    Also, on a side note, you're problem isn't really reading and writing XML in java, but seems more to be making your functionality generic so that any XML file can be split with your code.
    Regards
    JFM

  • JAXP DOM reading and writting issues

    import org.xml.sax.*;
    import org.w3c.dom.*;
    import javax.xml.parsers.*;
    import javax.xml.transform.*;
    import javax.xml.transform.dom.DOMSource;
    import javax.xml.transform.stream.StreamResult;
    import java.io.*;
    public class Test
    {   public static void main(String[] args) throws Exception
        {     DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            dbf.setIgnoringElementContentWhitespace(true);
         DocumentBuilder db = dbf.newDocumentBuilder();
         read(db, "xml_in.xml");
         create(db,"xml_out.xml");
        public static void read(DocumentBuilder db, String fileName)
        {     Document d = null;
         try
         {   d = db.parse(new File(fileName));
         }catch(IOException ex)
         {   ex.printStackTrace();
             return;
         }catch(SAXException ex)
         {   ex.printStackTrace();
             return;
         Node n = d.getDocumentElement();
         System.out.println("Name of the root element: " + n.getNodeName());
         NodeList nl = null;
         nl = d.getElementsByTagName("*");
         System.out.println("Number of element:" + nl.getLength());
         System.out.println();
         nl = d.getElementsByTagName("user");
         System.out.println("Length:" + nl.getLength());
         for(int i=0; i<nl.getLength(); i++)
         {   System.out.println("id: "+nl.item(i).getAttributes().getNamedItem("id").getNodeValue());
             System.out.println("name: "+nl.item(i).getFirstChild().getTextContent());
        public static void create(DocumentBuilder  db, String fileName) throws Exception
         Document d = db.newDocument();
         d.appendChild(d.createComment("This is comment"));
         Element ele_root = d.createElement("root");
         d.appendChild(ele_root);
         Element ele_temp;
         ele_temp = d.createElement("sub");
         ele_temp.setAttribute("id","1");
         ele_temp.appendChild(d.createTextNode("data"));
         ele_root.appendChild(ele_temp);
         ele_temp = d.createElement("sub");
         ele_temp.setAttribute("id","2");
         ele_root.appendChild(ele_temp);
         //adding node
         NodeList nl = d.getElementsByTagName("sub");
         Element ele_parent = (Element)nl.item(0).getParentNode();
         ele_temp = d.createElement("sub");
         ele_temp.setAttribute("id","3");
         ele_parent.appendChild(ele_temp);
         d.normalize();
         Transformer t = TransformerFactory.newInstance().newTransformer();
         //t.setOutputProperty(OutputKeys.METHOD, "test");
         t.transform(new DOMSource(d), new StreamResult(new File(fileName)));
    }xml_in.xml
    <?xml version = "1.0" ?>
    <user-detail>
         <user     id = "1"><name>user1</name><age>10</age></user>
         <user     id = "2">
              <name>user2</name>
              <age>20</age>
         </user>
         <user     id = "3">
              <name>user3</name>
              <age>30</age>
         </user>
    </user-detail>The result from read(db, "xml_in.xml"):
    >
    Name of the root element: user-detail
    Number of element:10
    Length:3
    id: 1
    name: user1
    id: 2
    name:
    id: 3
    name:
    >
    both name of id 2 and 3 are missing due to the spacing, how to remove the spacing to avoid this problem?
    The result from create(db,"xml_out.xml"):
    <?xml version="1.0" encoding="UTF-8" standalone="no"?><!--This is comment--><root><sub id="1">data</sub><sub id="2"/><sub id="3"/></root>how to set it nicely as below?
    <?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <!--This is comment-->
    <root>
         <sub id="1">data</sub>
         <sub id="2"/>
         <sub id="3"/>
    </root>thanks~

    Removing the whitespace is the wrong approach. Instead you should realize that the creators of that XML can put in whitespace wherever they feel like it, and more importantly, that the whitespace is also part of the document. In particular it forms text nodes which are children of the element in which they are located, just as element nodes are children.
    So your strategy of assuming that the "name" element will be the first child of the "user" element is incorrect. When there is whitespace before the "name" element, that whitespace will be the first child. So your strategy should be to get the "name" element which is a child of the "user" element.
    And by the way, calling the "normalize" method of the DOM won't do anything to affect that. As usual Ram manages to provide un-useful information.

  • How to read and write Xml file at client side using JavaScript !

    Hello,
    i am new to javascript.
    I have requirement to read and update XML file at client side.
    Will you please guide what could be the best way to read and update XMl file using javascript.
    Thanks,
    Zuned

    This is a Java forum,not a Javascript forum. Maybe you should ask here [http://www.webdeveloper.com/forum/forumdisplay.php?forumid=3&s|http://www.webdeveloper.com/forum/forumdisplay.php?forumid=3&s].

  • Read and Write XML files

    I work on a Flex application that will be used to record time entries for manufacturing plan. I have two problems to solve:
    1- Can I read an XML file from a local drive? (C: /temp/file)
    2- If the system where I call the web service is offline, I must create local file that are going to be read later vwhen the system will be up again. How can I create local file from Flex?

    A web-based app cannot access the local drive w/o user permission.
    Sometimes, folks upload local files to a server (also requiring user
    permission) and then request the file from the server.
    You can use local SharedObject to store data, although there are limits to
    how much data.
    The recommended option is to create an AIR app.  It will be able to access
    the local drive once it is installed.

  • About the exporting and importing xml data file in the pdf form

    Hi all,
    I need help for importing xml data file in the pdf form. When I write some thing in the text field with fill color and typeface (font) and exported xml data using email button. When I imported that xml file in the same pdf file that is used for exporting the xml data then all the data are shown in the control but not color and font typeface. Anyone has suggestion for solving this problem. Please help me for solving this problem.
    Thank you
    Saroj Neupane

    Can you post a sample form and data to [email protected] and I will have a look.

  • How to write XML into file using JSP

    Hello,
    I am parsing a XML file, then updating some of it content and trying to write back the updated file into the same location as an xml document but its not happening correctly....it gets written like this.
    &_lt;db_name&_gt;dataext&_lt;/db_name&_gt;
    Here is my code......somebody please advise
    <%@ page contentType="text/html"%>
    <%@ page import="java.io.*,
                        java.util.*,
                        org.jdom.*,
                        org.jdom.input.SAXBuilder,
                        org.jdom.output.*" %>
    <%
    String xml_file = "webapps/root/web-inf/admin.xml";
    SAXBuilder builder = new SAXBuilder("org.apache.xerces.parsers.SAXParser");
    Document l_doc = builder.build(new File(xml_file));
    Element root = l_doc.getRootElement();
    List admin = root.getChildren("db");
    Iterator loop = admin.iterator();
    while ( loop.hasNext()) {
         Element ele = (Element)loop.next();
         String state = ele.getChild("state").getText();
         String name = ele.getChild("db_name").getText();
         String ip = ele.getChild("db_ip").getText();
         if(state.equals("Florida")) {
              ele.getChild("db_ip").setText("209.11.111.1");
    XMLOutputter l_format = new XMLOutputter();
    String ls_result = l_format.outputString(l_doc);
    root.setText(ls_result);
    ls_result = l_format.outputString(l_doc);
    %>
    <html><head><title></title></head>
    <body>
    <%
         try {
              FileOutputStream ostream = new FileOutputStream("c:\\admin.xml");
              ObjectOutputStream p = new ObjectOutputStream(ostream);
              p.writeObject(ls_result);
              p.flush();
              ostream.close();
         catch(Exception e) {
              out.println(e.toString());
    %>
    </body>
    </html>     

    thanks amgandhi.....
    I found a solution for it, courtesy of this site:
    http://www.topxml.com/tutorials/main.asp?id=jdom&page=15
    <-********************************************************->
    import org.jdom.output.XMLOutputter;
    import org.jdom.*;
    import java.io.*;
    import java.util.*;
    // Write a program that creates document with a
    // single root element. Add a comment to the
    // root element, and assign the document's XML to
    // a local string. Finally, write the String to
    // System.out, and write the document to a text file.
    // For bonus points, allow the user to specify the
    // file name on the command line.
    public class ws3
    public static void main(String[] args)
    String filename = "default.xml";
    if(args.length > 0) filename = args[0];
    Element root = new Element("simple");
    Document doc = new Document(root);
    Comment cmt = new Comment("A bare document!");
    root.addContent(cmt);
    XMLOutputter outputter = new XMLOutputter(" ",
    true);
    String xml = outputter.outputString(doc);
    System.out.println(xml);
    writeToFile(filename, doc);
    private static void writeToFile(String fname,
    Document doc)
    try {
    FileOutputStream out =
    new FileOutputStream(fname);
    XMLOutputter serializer =
    new XMLOutputter(" ", true);
    serializer.output(doc, out);
    out.flush();
    out.close();
    catch (IOException e) {
    System.err.println(e);
    }

Maybe you are looking for