Writing XML Object to a File

Hi, I am using InDesign JavaScript to make an XML object in memory. When my script is done, I want to write the XML to a file. When I run the code below, the file is created, but the XML is not written to the file. Any help would be appreciated. Thanks. Rick
#target indesign
var partsMap = <partsMap />;
savePartsMap (partsMap);
function savePartsMap (partsMap) {
    var partsFile;
    // Make a File object for the parts map XML file.
    partsFile = new File("E:\\Test.xml");
    // Open the map file.
    partsFile.open("w");
    partsFile.write(partsMap);
    partsFile.close();

Add partsFile.encoding = 'UTF-8'; right after your File instantiation.
I'm not sure but you also might want to write partsMap.toXMLString() instead of the partsMap.toString() you're implicitly writing.
Jeff

Similar Messages

  • Writing XML Document to a file or the console

    How do i write an XML document to a file & to the console.
    Document doc = new Document
    doc = (Document)Class.forName("org.apache.xerces.dom.DocumentImpl").newInstance();
    Element root = doc.createElement("PERSON");
    Element item = doc.createElement("NAME");
    item.appendChild(doc.createTextNode("Vaskar"));
    root.appendChild(item);
    How do i write this doc object to the console

    if you use XMLDocument object which implements Document then you would be able to use the method print that is part of the xmlDocument class
    <BLOCKQUOTE><font size="1" face="Verdana, Arial">quote:</font><HR>Originally posted by Vaskar Dasgupta ([email protected]):
    How do i write an XML document to a file & to the console.
    Document doc = new Document
    doc = (Document)Class.forName("org.apache.xerces.dom.DocumentImpl").newInstance();
    Element root = doc.createElement("PERSON");
    Element item = doc.createElement("NAME");
    item.appendChild(doc.createTextNode("Vaskar"));
    root.appendChild(item);
    How do i write this doc object to the console<HR></BLOCKQUOTE>
    null

  • Writing InputStream object to a file.

    I want to write a InputStream object to a file. How can this be done?
    Help please

    Fucking spammer.
    http://forum.java.sun.com/thread.jspa?threadID=612286&messageID=3377965#3377965

  • Problems while writing xml doc to a  file

    Hi all , in my project (of distributed xml databases) i need to write the xml files from the main server to the clients.
    These xml files i had formed by fragmenting one xml doc and i did the fragmentation using ....
    TransformerFactory tf = TransformerFactory.newInstance();
              Transformer transformer = tf.newTransformer();
              transformer.transform(new DOMSource(root),
              new StreamResult(new FileOutputStream(outputFile)));
    Now the problem is that on the client where these fragments reside..i m not able to do the indexing of the document properly ie...
    some extra text nodes with no values are coming in the index...
    i dont know how to deal wid the extra nodes that i m getting after parsing the file and craeting an index for the same..
    may be its coz of the transformer func i m using....don know(???)
    Note : i m fragmenting the xml files into text files using the above function and then sending thm to the client via sockets.
    Also,after fragmenting i am getting sumthng like
    <?xml version="1.0" encoding="UTF-8"?>
    in all the files..is this a source of any problem....
    plz reply soon....

    You have not described how you "index" the files and what you mean by that.
    Are you processing them with SAX or DOM, or one of the variations of those means?
    Is there a chance that the "extra" nodes are simply text nodes with newlines ("\n")? There are usually a lot of extra text nodes in a file each containing only one newline.
    If you are using SAX, there is no requirement for the parser to collect all of the text inside an element into a single block before calling the characters method. You may get several calls to characters between the start of an element and the end. If you change parsers, you may even get a different number of calls, but the character data will always be the same.
    Dave Patterson
    As to the <?xml version="1.0" encoding="UTF-8"?> line, that is perfectly fine. It means that your file thinks it is valid XML. Whether or not it REALLY is valid depends on a validation of the file.

  • Emergency! Writing an object into a file (NotSerializableException)

    Hi, I am now working in a project. I came across a serialization problem which I am spending so many days and haven't gotten any solution.
    I assume that the problem is caused by the complexity of class design in a package. The saved object extends all of 9~11 classes in which some are abstract class, some are listening interface class, some are just normal class but extending from GUI components such as JTree, JFrame and so on. Besides static is spred over anywhere in the classes.
    code:(No problem here)
    output = new ObjectOutputStream( new eFileOutputStream( fileName ) );
    output.writeObject(prj);
    output.flush();
    Futher, the 'prj' object is proved to be very serializable as a result of "isSerializable()" function before writting in to a file. However it invokes IOExceptions, isn't it funny?
    ex:
    A--B--C--D--E
    |
    |
    F G H
    | |
    I J
    |
    prj
    In the example of above, is it possible to store all the state of objects A to J by storing prj so that I can re-construct the whole of objects relations and the members in them from the stored 'prj'?
    Back to the original problem, then...
    Do I have to get rid of all the static declarations of parent classes?
    Do I have to serialize each single classes one by one without being greedy tryint to store all of the state of objects linked to 'prj' at once?
    Do I have to get every single objects implemented 'Serializable' including abstruct and interface classes if they contains static declaration or someting unserializable?
    Please give me any help or hint, anything I am appreciate for.

    The problem is not very clear. Some code snippets might help. Especially the Exception details.Your object graph is somewhat confusing too.
    To answer your questions, the default Serialization (where the object prj, though extends java.io.Serializable, DOESN'T implement writeObject() and readObject() methods) will succeed only if all the reachable super classes in the graph are a. either implement Serializable or b. have no-argument constructors. In case of b., it's the responsibility of the object prj to re-establish the state of the parent classes from the serialized stream. You can do that by implementing writeObject() and readObject() methods themselves.
    The transient and static fields are never serialized. So if you want to preserve the value of a static field then you'll have to either a. explicitly serialize that field out to the ObjectOutputStream and read it back from the ObjectInputStream in the writeObject() and readObject() methods or b. using reflection where you can get the Class name and get the static field value from the corresponding 'Class' data type also using reflection (object.getClass().getField("fieldName").getValue(null)).

  • Writing xml from an .exe file

    Hi,
    So, is it possible to post to php in an .exe file instead of a .swf displayed inside a browser?
    If so, how? I figured if you just created the .exe on the server with the .php file in the same folder
    it would read it and work fine.
    This doesn't seem to be the case... any ideas? Does it always have to go through a browser page?
    thanks

    It is possible to call a PHP file from an EXE. Make sure that you have th PHP file in the webroot of your webserver (IIS or Apache). Also, make sure that you use the server path..for example: http://localhost/myapp/myphpfile.php. It should work!

  • Conversion of string into XML object

    Hi
    I am having some problems with conversion of string (containing XML data) into Flex XML object and binding it later to UI elements to output/maintain this data.
    Binding of XML structure to UI elements works perfectly fine if I will do following:
    1)      Hardcode XML object within Flex file
    2)      Read xml file from repository (xml file inside the Flex project)
    3)      Use HTTP request to retrieve XML data
    Unfortunately none of the above scenarios suits my solution.
    I am developing a prototype application for processing Flex forms inside SAP system. I have decided to make data bindings using XML structure stored in Data Base. When rendering form inside web browser based application I am retrieving corresponding XML schema (empty for new forms and populated for saved forms) and pass it to Flex form as a string type import parameter. Data is being passed correctly (I can display it on TextArea control for instance) but after conversion to XML and binding to DataGrid I am not getting any results.
    I am converting string (containing XML) to XML object in following way:
    Private var xml_obj:XML = new XML(string_xml );
    I am catching any potential errors but conversion is going well. After conversion I am not getting any results after binding it to DataGrid control and I am not able to access any of the nodes using AS code either. At the same time variable xml_obj is not empty (not null).
    Any help would be much appreciated.
    Regards
    Michael

    David
    First of all sorry for not stating it clearly but I am using Flex 3 for this development (at the moment it is the only choice when embedding Flex objects inside SAP applications).
    You must have missed the bit where I am describing how this XML data finds its way inside Flex. I am passing it to Flex as String type parameter during rendering (directly from DB where it is stored).
    Now, following code works perfect (XML is embedded inside Flex project):
                    <mx:XML id="form_data" source="../assets/example_xml_data.xml"/>
                    <mx:Script>
                                    <![CDATA[
                                                    import mx.collections.XMLListCollection;
                                                    import mx.controls.Alert;
                                                    [Bindable]
                                                    public var XML_list:XMLListCollection;
                                                    private function setParameters():void
                                                                   XML_list = new XMLListCollection(form_data.*);             
                                    ]]>
                    </mx:Script>
                    <mx:DataGrid id="myDataGrid" dataProvider="{XML_list}">
                                    <mx:columns>
                                                    <mx:DataGridColumn dataField="COMMON" headerText="Popular name"/>
                                                    <mx:DataGridColumn dataField="BOTANICAL" headerText="Botanical name"/>
                                                    <mx:DataGridColumn dataField="ZONE" headerText="Zone"/>
                                                    <mx:DataGridColumn dataField="LIGHT" headerText="Light"/>                                                                                                                                               
                                                    <mx:DataGridColumn dataField="PRICE" headerText="Price"/>                                               
                                                    <mx:DataGridColumn dataField="AVAILABILITY" headerText="Availability"/>                                    
                                    </mx:columns>               
                    </mx:DataGrid>
    But following code does not work (XML passed to Flex form as String input parameter):
    import sap.FlashIsland;
    import mx.controls.Alert;
    import mx.collections.XMLListCollection;
    [Bindable]
    public var xml_data:String;
    private var form_data:XML;
    [Bindable]
    private var XML_list:XMLListCollection;
    private function initApp():void
                    FlashIsland.register(this);
    private function setParameters():void
                    try
                                    form_data=new XML(xml_data);
                    catch (error:Error)
                                    Alert.show(error.toString());
                      XML_list = new XMLListCollection(form_data.*);           
    XML string does find its way inside Flex form. I can display content of variable xml_data in TextArea and all looks fine. Conversion to XML (variable form_data) goes well (no error)
    Please helpJ
    Regards
    Michael

  • Writing serialized objects as XML

    What are the advantages and a disadvantages for writing serialized objects as XML instead of the Java binary format?

    Depending on the serialization scheme, XML can be used to loosely bind the persistant data, so that the class can change version, or even be replaced by a different class as the project requires refactoring over its lifecycle.
    It also allows non-Java tools to interact with your data, which almost always has a longer lifetime than any implementation. I still occasionally process SGML files from the '80s. If they had been in a proprietory binary format, that data would be far harder to re-use.
    Pete

  • "encoding = UTF-8" missing while writing XML file using file Adapter

    Hi,
    We are facing an unique problem writing xml file using file adapter. The file is coming without the encoding part in the header of xml. An excerpt of the file that is getting generated:
    <?xml version="1.0" ?>
    <customerSet>
    <user>
    <externalID>51017</externalID>
    <userInfo>
    <employeeID>51017</employeeID>
    <employeeType>Contractor</employeeType>
    <userName/>
    <firstName>Gail</firstName>
    <lastName>Mikasa</lastName>
    <email>[email protected]</email>
    <costCenter>8506</costCenter>
    <departmentCode/>
    <departmentName>1200 Corp IT Exec 8506</departmentName>
    <businessUnit>1200</businessUnit>
    <jobTitle>HR Analyst 4</jobTitle>
    <managerID>49541</managerID>
    <division>290</division>
    <companyName>HQ-Milpitas, US</companyName>
    <workphone>
    <number/>
    </workphone>
    <mobilePhone>
    <number/>
    </customerSet>
    </user>
    So if you see the header the "encoding=UTF-8" is missing after "version-1.0".
    Do we need to configure any properties in File Adapter?? Or is it the standard way of rendering by the adapter.
    Please advice.
    Thanks in advance!!!

    System.out.println(nodeList.item(0).getFirstChild().getNodeValue());

  • Problem while writing to fixed length flat file from xml

    Hi,
    I have a problem in writing data into a flat file of fixed length...
    My input is a xml file and i want the output as a flat file. I am successful in converting the xml into flat file... But the main problem is, i am unable to insert spaces in between my fields in the flat file.
    The data in the flat file comes without spaces... Any suggestions on writing the schema...
    Regards
    Surya.

    Have a look at this doc
    http://otndnld.oracle.co.jp/document/products/as10g/101310/doc_cd/integrate.1013/b28994/nfb.htm#BGBBAJFD
    your element should be something like this, it pads with a space using the paddedBy expression
    <xsd:element name="C1" type="xsd:string" nxsd:style="fixedLength" nxsd:length="4" nxsd:paddedBy=" " nxsd:padStyle="tail" />if having trouble post what you want the file to look like, and the xsd you are using.
    cheers
    James

  • Writing XML files

    Hello all
    There's a vast amount of information on the java.sun.com site about parsing XML files:
    * creating DOM trees in memory from an XML file
    * setting up event handlers to be called when an XML file is parsed
    * transforming XML files using XSL.
    However, I can find very little information anywhere about writing XML files in the first place! I'm already aware of two ways to do this:
    (1) create a DOM in memory and write this to a file. If the data is large, though, this isn't feasible.
    (2) just output the XML elements directly to some file as text. This doesn't take account of the encoding, or special characters, and the document is not necessarily then syntactically valid.
    Is there some API which I haven't yet come across that is designed specifically for writing XML data to files? If it's built in to Java 2, then goodness knows how I've missed it all this time; if it's third-party, I'd be grateful for any links.
    Thanks for your help
    Rich Fearn

    I know pastes can be horrible, but this is a working example which I find useful: SAX XML output ;)
    import java.io.*;
    // SAX classes.
    import org.xml.sax.*;
    import org.xml.sax.helpers.*;
    //JAXP 1.1
    import javax.xml.parsers.*;
    import javax.xml.transform.*;
    import javax.xml.transform.stream.*;
    import javax.xml.transform.sax.*;
                    //AlphabetXMLOut(file, alphabets);
    class AlphabetXMLOut {
            public void run(){
                    try{
                            FileOutputStream fos = new FileOutputStream("output.xml");
                            PrintWriter out = new PrintWriter(fos);
                            StreamResult streamResult = new StreamResult(out);
                            // PrintWriter from a Servlet
                            //PrintWriter out = response.getWriter();
                            //StreamResult streamResult = new StreamResult(out);
                            SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
                            // SAX2.0 ContentHandler.
                            TransformerHandler hd = tf.newTransformerHandler();
                            Transformer serializer = hd.getTransformer();
                            serializer.setOutputProperty(OutputKeys.ENCODING,"ISO-8859-1");
                            serializer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,"users.dtd");
                            serializer.setOutputProperty(OutputKeys.INDENT,"yes");
                            hd.setResult(streamResult);
                            hd.startDocument();
                            AttributesImpl atts = new AttributesImpl();
                            // USERS tag.
                            hd.startElement("","","USERS",atts);
                            // USER tags.
                            String[] id = {"PWD122","MX787","A4Q45"};
                            String[] type = {"customer","manager","employee"};
                            String[] desc = {"Tim@Home","Jack&Moud","John D'oe"};
                            for (int i=0;i<id.length;i++){
                                    atts.clear();
                                    atts.addAttribute("","","ID","CDATA",id);
    atts.addAttribute("","","TYPE","CDATA",type[i]);
    hd.startElement("","","USER",atts);
    hd.characters(desc[i].toCharArray(),0,desc[i].length());
    hd.endElement("","","USER");
    hd.endElement("","","USERS");
    hd.endDocument();
    fos.close();
    }catch (IOException e){
    System.err.println ("Unable to write to file");
    System.exit(-1);
    }catch (TransformerConfigurationException tce){
    System.err.println("Error in: TransformerConfigurationException");
    }catch (SAXException spe) {
    // Error generated by the parser
    System.err.println("Error in: (SAXException");
    // Use the contained exception, if any
    Exception x = spe;
    if (spe.getException() != null)
    x = spe.getException();
    x.printStackTrace();
    -Hope this helps

  • Writing JAXRPC Object to XML Stream  by using LiteralObjectSerializerBase

    I am trying to write the JAX-RPC object to a file before I dispatch it to the service provider. What I currently have is :
    QName type = new QName("http://solms.co.za/utils/appsupport", "LicenseRequest");
    XMLWriter writer = XMLWriterFactory.newInstance().createXMLWriter(System.out); 
    LicenseRequest_LiteralSerializer serializer = new LicenseRequest_LiteralSerializer(type, "", AppSupportService_SerializerRegistry.ENCODE_TYPE);
          serializer.initialize(new InternalTypeMappingRegistryImpl(new AppSupportService_SerializerRegistry().getRegistry()));
          serializer.doSerialize(licenseRequest,writer,new SOAPSerializationContext());But it does not work. I have the feeling I am not far off, but still mis something.
    Thanks

    Convert the method signature to a string (such as it is in the class file), and persist that.

  • Need help (desperately) '^_^ in writing multiple objects in a single file

    For all those Java guru out there please help me,
    I want to write a simple application that can serialize objects in a single file. Currently I know how to serialize one object in one file using the ObjectOutputStream's writeObject () method.But the problem is that if i have 10.000 objects to serialize then I will have 10.000 file in my HD. To simplify things I want to write those 10.000 objects in a single file. But I dont know how to do that, any one can help ??

    You can write any number of objects of any type into a file when you serialize them. You need to realize that once they're written to the file, they're all placed in there as type Object, so there really isn't any distinction between any of them. You don't have a file that contains only Shapes, or only Images. You write them out as Objects, and then you discover their types later as your deserialize them and read them in. You should read into the "Reflection" capabilities that all objects have. You write an Image to a file, and then a Shape, and then a Color, you can later pack these all into an ArrayList as you read them in, and when you use them discover their type using reflection.
    -Jason Thomas.

  • Trouble writing to object array

    Hi I did a semester of java 2 years ago and I'm trying to remember what I knew so please bear with me...
    I am extracting data from an xml file and then writing that information to an object array called files containing 4 string and 1 array. This files array is in turn an element in another object array containing 400 files arrays called records.
    It appeared to be working but when I want it to print out which ever record I have selected it only prints out the last record! It seems to be overwriting each files array with the next?
    Another problem I can only print out an element of the array not the entire thing?
    Please help have spent weeks on this
    Here is the code:
    Object[] Records = new Object[400];
    Object files[] = new Object[5];
    NodeList records = doc.getElementsByTagName("record");
    for( int i = 0; i < records.getLength();i++)
    Element record = (Element) records.item(i);
    NodeList headers = record.getElementsByTagName("header");
    Element header = (Element) headers.item(0);
    NodeList ids = header.getElementsByTagName("identifier");
    for(int j = 0; j < ids.getLength(); j++){
    Element id = (Element) ids.item(j);
    String ID = getText(id);
    files[0] = ID;
    NodeList metadatas = record.getElementsByTagName("metadata");
    Element metadata = (Element) metadatas.item(0);
    NodeList citeseers = metadata.getElementsByTagName("oai_citeseer:oai_citeseer");
    Element citeseer = (Element) citeseers.item(0);
    NodeList titles = citeseer.getElementsByTagName("dc:title");
    for(int k = 0; k < titles.getLength(); k++){
    Element title = (Element) titles.item(k);
    String TITLE = getText(title);
    files[1] = TITLE;
    NodeList subjects = citeseer.getElementsByTagName("dc:subject");
    for(int m = 0; m < subjects.getLength(); m++){
    Element subject = (Element) subjects.item(m);
    String SUBJECT = getText(subject);
    files[2] = SUBJECT;
    NodeList descriptions = citeseer.getElementsByTagName("dc:description");
    for(int n = 0; n < descriptions.getLength(); n++){
    Element description = (Element) descriptions.item(n);
    String DESCRIPTION = getText(description);
    files[3] = DESCRIPTION;
    String[] Names = new String[20];
    NodeList authors = citeseer.getElementsByTagName("oai_citeseer:author");
    for(int l = 0; l < authors.getLength(); l++){
    Element author = (Element) authors.item(l);
    Names[l] = author.getAttribute("name");
    files[4] = Names;
    System.out.println("The id is "+files[0]);
    System.out.println("The title is "+ files[1]);
    System.out.println("The Subject is "+ files[2]);
    System.out.println("The Description is "+ files[3]);
    for(int q=0; q < authors.getLength(); q++){
    System.out.println("The Names are "+ ((String[])files[4])[q]);
    //Records[i] = files;
    System.out.println(((Object[])Records[0])[0]);

    I'm afraid I'm not going to make you a millionaire but I feel so relieved at the moment that if I had a million I'd give it to you!!Yeah, I know you won't make me a millionaire, but I can dream... :)
    thanks for all your helpYou are welcome. Do you understand why you needed to move the creation of the "files" array.

  • Appending XML data to a file using file adaptor

    Hi,
    I am trying to append data to a file using file adaptor in XML format. (Objective is to store data as XML message in the file). I understand it is possible to append data to an existing file by making appropriate changes in WSDL manually. However, my issue is every time the XML data is appended to a file even the XML header message is also getting appended. As a result the file data does not adhere to defined schema structure anymore.
    Is there a way to save XML data in a file in append mode ?
    Thanks, Riz

    I am having the same issue as well, which makes the output XML an invalid one. I have an XSD that has a hierarchy of elements. whenever I am wiriting the child elements the header message & the name space is also getting written. For example
    <?xml version="1.0" ?><Parent xmlns="http://testSchema.com/outputSchema">
    <StartDate>01/01/2001</StartDate>
    <EndDate>01/30/2001</EndDate>
    <Child/>
    </Parent>
    <?xml version="1.0" ?><Child xmlns:ns1="http://testSchema.com/outputSchema">
    <ns1:Id>20012981</ns1:Id>
    <ns1:Value/>
    <ns1:Date>01/15/2001</ns1:Date>
    </Child>
    <?xml version="1.0" ?><Child xmlns:ns1="http://testSchema.com/outputSchema">
    <ns1:Id>20012981</ns1:Id>
    <ns1:Value/>
    <ns1:Date>01/15/2001</ns1:Date>
    </Child>
    I am using a onefile adapter partnerlink to write the parent & an another one for writing the child element, since the child elements will repeat more than once. One other way to fix this issue is write the data using java embedded activity, but that would need a lot of boiler plate code, for writing/reading/appending the same file & for handling all those IOexceptions & buffer IN/outs. I am curious if someone had the same issue & how they resolved it.

Maybe you are looking for