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

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

  • 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].

  • How to read and write a data from extrenal file

    Hi..
    How to read and write a data from extrenal file using Pl/sql?
    Is it possible from Dyanamic Sql or any other way?
    Reagards
    Raju

    utl_file
    Re: How to Create text(dat) file.
    Message was edited by:
    jeneesh

  • 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

  • Windows 2008 R2 Folder assign permission "Read and Write" problem with *.doc file

    Hello All,
    I am a new one here,
    I am sorry for any mistakes and also my english is so poor.
    M Brother company runing Windows 2008 R2 as Active Directory...
    We have folder Name: Admin
    and in this folder, there are alot documents files as : *.doc, *.dwg, *.txt etc.....
    All user accesing to these files and they can open to edit and save...
    One day my brother want me to set Admin folder for all users just"Read and Write.." mean they still can open files to edit and save... but can't delete..
    I did success with this..
    But only one thing happen.. when they open *.doc file to edit and attempting to save, the message alert" access denide " and they can only "SAVE AS"...We don't want "Save as"
    Could you show me how can we fix error with *.doc file while they trying to save? because it allow only save as.. but other files as *.text file or *.dwg they can save without problem..
    Could expert here ever face this issues and fix by yourself, please share me with this..
    Please help me..
    Best regards,

    Hi,
    Office programs are specific. They will create a temp file when edit, then the temp file will be deleted when close. So Delete permission is needed for users to saving Office files like Excel/Word.
    For more detaile information, please refer to the thread below:
    Special Permissions - User cannot save files
    http://social.technet.microsoft.com/Forums/windowsserver/en-US/721fb2f1-205b-46e5-a3dc-3029e5df9b5b/special-permissions-user-cannot-save-files
    Best Regards,
    Mandy 
    Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Subscriber Support, contact [email protected]

  • What is the best combination of read and write objects to binary files ...

    Hi everyone,
    what are the best combination of read and write objects to read/write a record of customers from a binary file. I should be able to use StringTokenizer. I am bit confused with all these Stream reader and writers.
    abdul

    You are, indeed, confused:
    o StreamTokenizer works on character input, not binary input.
    o Readers and Writers in general work on character streams, not binary.
    That leaves you various input streams and output streams for reading binary data.

  • Anyone have example stylesheet for Flatten to XML output

    I would like to log the output of a "flatten to xml" vi and display it in a tabular format in my Teststand xml report.  I'm wondering if anyone has a starting point for the stylesheet side of things.

    Almost there....
    I have a properly formated XML string from Labview to Teststand.  I have the XSL which has been tested and added to my horizontal.xsl used by the Teststand report.  My problem now is that when I log the XML string using Additional Results, Teststand is putting the CDATA tag around the string preventing it from using my XSL.   Is there a flag or something to set so Teststand will add the XML as is.
    I've done this before using the ModifyReportHeader callback and the GetXML method, but the ModifyReportEntry doesn't work for XML reports.  So I really need to know how to stick my XML in the report from my client sequence file without Teststand altering it.
    Thanks,
    Kevin
    Attachments:
    Capture.PNG ‏5 KB

  • 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.

  • Read and write compressed data from blob in ADF

    Hi All,
    I have a requirement where i need to compress/zip the file, if the file is greater than 2MB and store in database.
    And i need to extract it from database in download dialog as zip file.
    Please suggest me, i m using JDev 10.1.3.5 and using inputFile component or please redirect me to any examples or demos.
    Regards,
    R N V Prasad

    Hi
    I am first uploading file and if the file is more than 2MB, i am compressing it. i used the below method for compressing.
    public void zipFile(String inputFilePath,String outputFilePath,String outFileName){
    long fileSize;
    long twoMBFileSize=2097152;
    String outFileLocation;
    try
    byte[] data = new byte[1000];
    File file=new File(inputFilePath);
    FileInputStream fis=new FileInputStream(file);
    BufferedInputStream in = new BufferedInputStream(fis);
    fileSize = file.length();
    System.out.println("File size.."+fileSize);
    int count;
    outFileLocation=outputFilePath+outFileName;
    System.out.println("outFileLocation..."+outFileLocation);
    ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(outFileLocation)));
    out.putNextEntry(new ZipEntry(outFileName));
    while((count = in.read(data,0,1000)) != -1)
    out.write(data, 0, count);
    in.close();
    out.flush();
    out.close();
    catch(Exception e)
    e.printStackTrace();
    And i will read the compressed file and posting to DB.
    Here i am facing the problem while downloading the compressed files.
    Naga

  • How to read and write in a binary file?

    Hi all,
    how can i search in a binary file for string and replace this string with another
    bin file ...test.bin
    search String "DE AD FA 01"
    regards
    gebi

    You need to install Google on your computer. That way, you can search for all the information on that algorithm available on the Internet.

  • Im trying to sign into my adobe profile and keep asking me for my serial number of any recently purchased promgrams but i dont have any register products since the only product i have is aadobe reader and i downloaded it from the google play store....i am

    wassup

    Branching this to a separate discussion.
    Idontextistyt were you previously able to utilize your Creative Cloud Membership or have you always been prompted to enter a serial number?  Also which operating system are you using?  Finally are you on a managed network?

  • How to read and write data from json file from windows phone7 app

    Hi
    I am developing wp7 app for the use of students my questions are
    How can i write a code to read and write the json/text file for the wp7.
    I am using windows 7 OS, VS 2010 Edition.
    This is my code below:
    xaml:
    <Grid>
                        <TextBlock Height="45" HorizontalAlignment="Left" Margin="7,18,0,550" Name="textBlock1" Text="Full
    Name: " />
                        <TextBox Width="350" Height="70" HorizontalAlignment="Left" Margin="108,1,0,0" Name="txtName"
    Text="Enter your full name" VerticalAlignment="Top" />
                        <TextBlock Height="45" HorizontalAlignment="Left" Margin="6,75,0,0" Name="textBlock2" Text="Contact
    No: " VerticalAlignment="Top" />
                        <TextBox Width="350" Height="70" HorizontalAlignment="Left" Margin="108,61,0,480" Name="txtContact"
    Text="Enter your contact number" MaxLength="10" />
                        <Button Content="Register" Height="72" HorizontalAlignment="Left" Margin="10,330,0,0" Name="btnRegister"
    VerticalAlignment="Top" Width="190" Click="btnRegister_Click" />
                    </Grid>
    xaml.cs:
    private void btnRegister_Click(object sender, RoutedEventArgs e)
                string name, contact;
                name = txtName.Text;
                contact = txtContact.Text;
                try
                    if (name != "" && contact != "")
                        string msg = name + " " + contact;
                        MessageBox.Show(msg);
                        Student stud = new Student
                            Name= name,
                            Contact = contact,
                        string jsonString = JsonConvert.SerializeObject(stud);
                        MessageBox.Show(jsonString);
                    else
                        MessageBox.Show("Input Proper Information", MessageBoxButton.OK);
                catch (Exception ex)
                    MessageBox.Show(ex.Message);
    I have download NewtonSoft.json version 5.0.8.
    So, I am able to convert input data into json format, but how can I able to write and read this data from a json/text file.
    How can I do?
    Thank you in adv and please, reply soon.

    We don't have many samples left for Windows Phone 7 + Azure, the closest one to what you want to do is probably:
    Using Local Storage with OData on Windows Phone To Reduce Network Bandwidth
    this sample uses the local database feature: 'LINQ to SQL', available to Windows Phone 7.1 and 8.0 Silverlight applications, instead of simple file storage but even if you choose to stick with simple file storage I believe you should be able to adapt the
    networking related portions of the sample to your particular application.
    Eric Fleck, Windows Store and Windows Phone Developer Support. If you would like to provide feedback or suggestions for future improvements to the Windows Phone SDK please go to http://wpdev.uservoice.com/ where you can post your suggestions and/or cast
    your votes for existing suggestions.

  • Reading and writing to a text file from an Applet

    I'm a novice java programming with very little formal programming training. I've pieced together enough knowledge to do what I've wanted to do so far...
    However, I've been unable to figure out how to read and write to a text file from an Applet (I can do it from a normal java program just fine). Here is a simple example of what I'd like to do (you can also look at it on my website: www.stat.colostate.edu/~leach/test02/test02.html). I know that there is some problem with permission/security but I'm not smart enough to understand what the error messages are telling or understand the few books I have. If anyone can tell me how to get this applet to work, or direct me to some referrences that would help me out I'd really appreciate it.
    Thanks,
    Andy
    import java.applet.Applet;
    import java.net.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.io.*;
    public class test02 extends Applet {
    public Button B_go;
    public GridBagConstraints c;
    public void init() {
    this.setLayout(new GridBagLayout());
    c = new GridBagConstraints();
    c.fill = GridBagConstraints.BOTH;
    B_go = new Button("GO");
    c.gridx=1; c.gridy=0; c.gridwidth=1; c.gridheight=1;
    c.weightx = c.weighty = 0.0;
    B_go.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
    print_stuff();
    setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
    this.add(B_go,c);
    public static void print_stuff() {
    try{
    File f = new File("test02.txt");
    PrintWriter out = new PrintWriter(new FileWriter(f));
    out.print("This is test02.txt");
    out.close();
    }catch(IOException e){**/}
    }

    I have almost the exact same problem, and I am in the same situation as you are with respects to the language.
    I am simply trying to create a file and output some garbage to it but my applet always spits back a security violation. I've tried eliminating the restrictions on the applet runner I use but I still get the error.
    My method:
    debug = new Label() ;
    debug.setLocation( 20, 20 ) ;
    debug.setSize( 500, 15 ) ;
    add( debug ) ;
    // output
    try
         OutputStream file = new FileOutputStream( new File( "" + getCodeBase() + "output.txt" ) ) ;
         byte[] buffer = { 1, 2, 3, 4, 5 } ;
         file.write( buffer ) ;
         file.close() ;
    } catch( Exception e )
         debug.setText( e.toString() ) ;
         Can anyone tell why this isnt working?

  • Read and write existing xml file trouble !

    Hi everyone ! 
    i'm trying to save hight score of user in my game by using a xml file , in my xml file has element <best_score>0<best_score/>
    and my code to do it is : 
     XElement best=XElement.Load("Assets/best.xml");
                IEnumerable<XElement> loc = best.Elements("best_score");
                foreach (XElement elem in loc)
                    int check=Convert.ToInt32(elem.Value.ToString());
                    int score_user = Convert.ToInt32(scores.ToString());
                    if (score_user >= check)
                       hight_score.Text = score.ToString();
                         elem.Value = scores.ToString();
                         // what code to save this  xml file  after modify ?????
                    else
                        list_box.Text = check.ToString();
    i down know what method can help me save my xml file after update hight score of user in this case .  
    Anyone has an idea to solve it for me ? please , thanks you ! 
    sorry about my english ! 

    Hi,
    It is not recommended to update a file withing the project, so you need to store it in the IsolatedStorage.
    Here is a sample to read and write file in IsolatedStorage,
    XDocument xDoc;
    var file = Util.ReadFile("XMLFile.xml");
    if (file != null)
    xDoc = XDocument.Parse(file);
    var bestScore = xDoc.Element("best_score").Value;
    //do calculation
    xDoc.Element("best_score").Value = "200";
    Util.SaveFile("XMLFile.xml", xDoc.ToString());
    For the above code to work, you need to have a file named "XMLFile.xml" in your IsolatedStorage, with data as  "<best_scrore>200</best_scrore>"
    To read and write file:
    public static class Util
    public static void SaveFile(string filename, string data)
    try
    using (var store = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication())
    using (var stream = new IsolatedStorageFileStream(filename, FileMode.Create, FileAccess.ReadWrite, store))
    StreamWriter writer = new StreamWriter(stream);
    writer.Write(data);
    writer.Close();
    catch (Exception)
    Debug.WriteLine("Couldn't save the file.");
    public static string ReadFile(string filename)
    try
    String data;
    if (!IsolatedStorageFile.GetUserStoreForApplication().FileExists(filename)) return null;
    using (var store = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication())
    using (var stream = new IsolatedStorageFileStream(filename, FileMode.Open, FileAccess.ReadWrite, store))
    StreamReader stmReader = new StreamReader(stream);
    data = stmReader.ReadToEnd();
    stmReader.Close();
    return data;
    catch (Exception)
    return null;
    Pradeep AJ

Maybe you are looking for

  • Urgent help needed in code

    Hi iam copying data to table control from ztable. say i copied into my table control 20 rows. sayy i have my 18 row material field incorrect, i have an error message. for some reason my loop in PAI does looping for only first 11 rows. After the 11 ro

  • What technologies are to be used for Web2.0 application

    Hi All!! I am developing a Web 2.0 website in JAVA. But I am little confused in deciding upon the technologies to be used. I would like to use the following technologies in my application but not sure whether its a good choice or not. Presentation Ti

  • How do I install Elements 11 purchased on disk on to a macbook without a disk drive?

    I have recently purchsed Elements 11 and installed it on my iMac.  I now want to install it on my MacBook Pro but it does not have a disk drive.  How can I do this? I understand that it can be used on upto two computers.

  • Unable to rearrange pages in Acrobat XI

    On iMac 3.1 Ghz Intel Core i5 OS 10.7.5, using recently installed Adobe Acrobat Pro 11.0.04 In an Acrobat XI pdf that has had pages inserted from other Acrobat XI pdf documents, in the thumbnail view, either clicking on or command clicking on page th

  • Why does Firefox not update automatically nor allow me to manually update?

    I'm running version 3.0.5, but didn't notice it wasn't updating until websites started complaining recently. When I try to upload manually from the website, the program downloads but will not copy into my applications folder. It says there is already