How to create a Document from a Node?
Howdy,
I'm cross posting this from http://forum.java.sun.com/thread.jspa?threadID=737347&tstart=0 because I didn't get a nibble after half an hour or so...
I expected this code to produce:
<?xml version="1.0" encoding="UTF-16"?>
<one>hello world</one>but instead I get Object's toString:
org.apache.crimson.tree.XmlDocument@18a992fPlease does anyone know which implementation of Document overrides the toString() method to produce xml?
... I'm stuck on java 1.4.2_11 ...
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import java.io.ByteArrayInputStream;
class NodeToDocumentConverter
public static void main(String[] args) {
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
ByteArrayInputStream bais = new ByteArrayInputStream("<test><one>hello world</one></test>".getBytes());
Document doc1 = db.parse(bais);
Node node = doc1.getElementsByTagName("one").item(0);
Document doc2 = db.newDocument();
doc2.appendChild(doc2.importNode(node, true));
System.out.println(doc2.toString());
} catch (Exception e) {
e.printStackTrace();
}Thanking you, Keith.
Here's the final version... the fun part was using reflections to print the stack-trace of the root cause exception (if any).
forums/DomSerializer3.java
// http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JAXPXSLT4.html
package forums;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.xml.sax.SAXException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.ByteArrayInputStream;
import java.lang.reflect.Method;
import krc.utilz.ExceptionHandler;
class DOMSerializerException extends java.lang.RuntimeException {
private static final long serialVersionUID = 546980432534L;
DOMSerializerException() {
super();
DOMSerializerException(String message) {
super(message);
DOMSerializerException(String message, Throwable cause) {
super(message, cause);
DOMSerializerException(Throwable cause) {
super(cause);
class DOMSerializer
// get a transformer from the factory
private final TransformerFactory transformerFactory;
private final Transformer transformer;
public DOMSerializer() {
try {
transformerFactory = TransformerFactory.newInstance();
transformer = transformerFactory.newTransformer();
} catch (TransformerConfigurationException e) { //from newInstance
e.printStackTrace();
throw new DOMSerializerException("TransformerFactory.newInstance failed: "+e, e);
public void serialize(org.w3c.dom.Document document, java.io.OutputStream outputStream) {
try {
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(outputStream);
transformer.transform(source, result);
} catch (TransformerException e) { //from newInstance
e.printStackTrace();
throw new DOMSerializerException("Transformer.transform failed: "+e, e);
public class DomSerializer3
public static void main(String[] args){
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
ByteArrayInputStream input = new ByteArrayInputStream("<test><one>hello world</one></test>".getBytes());
Document originalDocument = builder.parse(input);
Node node = originalDocument.getElementsByTagName("one").item(0);
Document newDocument = builder.newDocument();
newDocument.appendChild(newDocument.importNode(node, true));
DOMSerializer serializer = new DOMSerializer();
serializer.serialize(newDocument, System.out);
} catch (DOMSerializerException e) {
System.err.println(e.toString());
ExceptionHandler.printLowestStackTrace(e);
} catch (Exception e) {
e.printStackTrace();
krc/utilz/ExceptionHandler.java
// http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JAXPXSLT4.html
package krc.utilz;
import java.lang.reflect.Method;
public abstract class ExceptionHandler
public static void print(org.xml.sax.SAXParseException e) {
System.err.println(
"org.xml.sax.SAXParseException: "+e.getMessage()
+ ", line "+e.getLineNumber()
+ ", uri "+e.getSystemId()
printLowestStackTrace(e);
public static void print(java.lang.Exception e) {
System.err.println(e.toString());
printLowestStackTrace(e);
* Prints the stackTrace of the lowest level exception.
* </p>
* if possible invokes e.getException().printStackTrace()
* else if possible invokes e.getCause().printStackTrace()
* otherwise invokes e.printStackTrace()
public static void printLowestStackTrace(Exception e) {
Throwable x = null;
// try getException
try {
Method method = e.getClass().getDeclaredMethod("getException");
method.setAccessible(true);
x = (Throwable) method.invoke(e);
} catch (Exception eaten) { //NoSuchMethodException, IllegalAccessException
// do nothing
// else getCause
if (x==null) {
try {
Method method = e.getClass().getDeclaredMethod("getCause");
method.setAccessible(true);
x = (Throwable) method.invoke(e);
} catch (Exception eaten) { //NoSuchMethodException, IllegalAccessException
// do nothing
// otherwise default to e itself
if (x==null) {
x = e;
x.printStackTrace();
}In a "real" application DOMSerializerException and DOMSerializer would be public classes under krc.utilz.domz... and DomSerializer3 would become krc.utilz.domz.test.DomSerializerTest. All in one file will do for a quick prototype.
Thanx ejp. I really appreciate your thoughtful comments. Yeah reply 3 was the result of a minor brain explosion, but it's all right, I got better!
On exception handling... I prefer to throw unchecked exceptions for everything except the expected use-cases like FileNotFoundException or NoRowsException or InsufficientFundsException... everything else percolates automagically (with NO intervening exception handling code) up to the fault barrier at the top of the component (or layer)... after all what-the-frag am I (or the user) expected to do with a javax.xml.transform.TransformerConfigurationException error except spit, quit, and call those-wankas-in-IT-support-to-sort-it-out? O hang on, that's me... and I would expect to have to deal with this manually... The root cause is probably a installation or configuration issue after all... not something the program can deal with on the fly.
Cheers, and thanx again. Keith. It's beer o'clock :-)
Edited by: corlettk on Nov 10, 2007 7:15 AM
Similar Messages
-
DOM - create new document from part of other document
Hi.
How to create a document from part (sub tree) of the other document?
document 1.
<?xml version="1.0" encoding="UTF-8"?>
<root>
<meta1>blaa blaa</meta1>
<meta2>blaa2 blaa2</meta2>
<data>
<info>
<name></name>
</info>
</data>
</root>
document 2 shuold be:
<?xml version="1.0" encoding="UTF-8"?>
<data>
<info>
<name></name>
</info>
</data>
Or can I just remove root and meta elements?Something like this:DocumentBuilder db = // create a DocumentBuilder;
Document newDoc = db.newDocument();
Node newRoot = // the Element you want to be the root of the new document;
Node root = newDoc.adoptNode(newRoot);
newDoc.appendChild(root); -
How to create a document folder using ListData.svc
Hi All,
I've recently been put on a project where I need to use the REST services (ListData.svc) to retrieve and add documents to the document library. It all has been smooth sailing until I hit the point where I want to save a document in a path that doesn't exist.
I get an error if I try to save a file where the folder structure doesn't exist. I then went about it a different way trying to create the folder structure first. This also didn't work and I get an error message saying that the entity type is marked with the
MediaEntry attribute but no save stream was set for the entity. Not too sure what set for the save stream if I'm just adding a folder.
So my question is can a file be added to a folder structure that doesn't exist where it automatically creates the folders. If not can the service create folders?
Some sample code I've been using:
var folder = new SampleDocumentLibraryItem();
folder.Name = "Sample";
folder.Title = "Sample";
folder.ContentType = "Folder";
folder.Path = "/sample/folder1/folder2";
spContext.AddToSampleDocumentLibrary(folder);
spContext.SaveChanges();
Thanks in advance,
DamoHi All,
Finally managed to figure this one out. For anyone who needs source on how to create a document folder. Some sample source is below...
var folder = new DocumentLibraryItem();
folder.Name = "Folder Name";
folder.Title = "Folder Name";
folder.ContentType = "Folder";
folder.Path = path;
spContext.AddtoDocumentLibrary(folder);
spContext.SetSaveStream(folder, stream, false, folder.ContentType, folder.Path + folder.Name + "|0x0120009BCC19899CEBC6468FF4EEAC7B8CF4F5"
spContext.SaveChanges();
So the important differences in the code above. The content type of the object and stream MUST be set to "Folder". I'm not sure why but you still need to set the save stream to be a valid stream even though you're only adding a folder. So just keep the stream
open and then pass "true" to close it when you actually save the file. The other important element as noted from the URL's in the previous comments is you need to add a "|" + Content Type ID of a folder. You'll be able to get this ID by visiting the rest service
for an existing document library and view source to see the actual content type id for a folder.
Thanks everyone for your help,
Damo -
Hi,
The requirement is to create ""Document Sets in Bulk" using JSOM. I am using the following posts:-
http://blogs.msdn.com/b/mittals/archive/2013/04/03/how-to-create-a-document-set-in-sharepoint-2013-using-javascript-client-side-object-model-jsom.aspx
http://social.msdn.microsoft.com/Forums/sharepoint/en-US/1904cddb-850c-4425-8205-998bfaad07d7/create-document-set-using-ecma-script
But, when I am executing the code, I am getting error "Cannot read property 'DocumentSet' of undefined "..Please find
below my code. I am using Content editor web part and attached my JS file with that :-
<div>
<label>Enter the DocumentSet Name <input type="text" id="txtGetDocumentSetName" name="DocumentSetname"/> </label> </br>
<input type="button" id="btncreate" name="bcreateDocumentSet" value="Create Document Set" onclick="javascript:CreateDocumentSet()"/>
</div>
<script type="text/javascript" src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2.min.js"> </script>
<script type="text/javascript">
SP.SOD.executeFunc('sp.js','SP.ClientContext','SP.DocumentSet','SP.DocumentManagement.js',CreateDocumentSet);
// This function is called on click of the “Create Document Set” button.
var ctx;
var parentFolder;
var newDocSetName;
var docsetContentType;
function CreateDocumentSet() {
alert("In ClientContext");
var ctx = SP.ClientContext.get_current();
newDocSetName = $('#txtGetDocumentSetName').val();
var docSetContentTypeID = "0x0120D520";
alert("docSetContentTypeID:=" + docSetContentTypeID);
var web = ctx.get_web();
var list = web.get_lists().getByTitle('Current Documents');
ctx.load(list);
alert("List Loaded !!");
parentFolder = list.get_rootFolder();
ctx.load(parentFolder);
docsetContentType = web.get_contentTypes().getById(docSetContentTypeID);
ctx.load(docsetContentType);
alert("docsetContentType Loaded !!");
ctx.executeQueryAsync(onRequestSuccess, onRequestFail);
function onRequestSuccess() {
alert("In Success");
SP.DocumentSet.DocumentSet.create(ctx, parentFolder, newDocSetName, docsetContentType.get_id());
alert('Document Set creation successful');
// This function runs if the executeQueryAsync call fails.
function onRequestFail(sender, args) {
alert("Document Set creation failed" + + args.get_message());
Please help !!
Vipul JainHello,
I have already tried your solution, however in that case I get the error - "UncaughtSys.ArgumentNullException: Sys.ArgumentNullException:
Value cannot be null.Parameter name: context"...
Also, I tried removing SP.SOD.executeFunc
from my code, but no success :(
Kindly suggest !!!
Vipul Jain -
Heap space error while creating XML document from Resultset
I am getting Heap space error while creating XML document from Resultset.
It was working fine from small result set object but when the size of resultset was more than 25,000, heap space error
I am already using -Xms32m -Xmx1024m
Is there a way to directly write to xml file from resultset instead of creating the whole document first and then writing it to file? Code examples please?
here is my code:
stmt = conn.prepareStatement(sql);
result = stmt.executeQuery();
result.setFetchSize(999);
Document doc = JDBCUtil.toDocument(result, Application.BANK_ID, interfaceType, Application.VERSION);
JDBCUtil.write(doc, fileName);
public static Document toDocument(ResultSet rs, String bankId, String interfaceFileType, String version)
throws ParserConfigurationException, SQLException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.newDocument();
Element results = doc.createElement("sims");
results.setAttribute("bank", bankId);
results.setAttribute("record_type", "HEADER");
results.setAttribute("file_type", interfaceFileType);
results.setAttribute("version", version);
doc.appendChild(results);
ResultSetMetaData rsmd = rs.getMetaData();
int colCount = rsmd.getColumnCount();
String columnName="";
Object value;
while (rs.next()) {
Element row = doc.createElement("rec");
results.appendChild(row);
for (int i = 1; i <= colCount; i++) {
columnName = rsmd.getColumnLabel(i);
value = rs.getObject(i);
Element node = doc.createElement(columnName);
if(value != null)
node.appendChild(doc.createTextNode(value.toString()));
else
node.appendChild(doc.createTextNode(""));
row.appendChild(node);
return doc;
public static void write(Document document, String filename) {
//long start = System.currentTimeMillis();
// lets write to a file
OutputFormat format = new OutputFormat(document); // Serialize DOM
format.setIndent(2);
format.setLineSeparator(System.getProperty("line.separator"));
format.setLineWidth(80);
try {
FileWriter writer = new FileWriter(filename);
BufferedWriter buf = new BufferedWriter(writer);
XMLSerializer FileSerial = new XMLSerializer(writer, format);
FileSerial.asDOMSerializer(); // As a DOM Serializer
FileSerial.serialize(document);
writer.close();
} catch (IOException ioe) {
ioe.printStackTrace();
//long end = System.currentTimeMillis();
//System.err.println("W3C File write time :" + (end - start) + " " + filename);
}you can increase your heap size..... try setting this as your environment variable.....
variable: JAVA_OPTS
value: -Xms512m -Xmx1024m -XX:PermSize=256m -XX:MaxPermSize=512m -
Create Billing Document from Sales Order (Without Delivery)
Dear Experts,
Pls note, presently we are creating Billing Document (VF01) from Outbound Delivery Number after Post Good Issue. All sales Document like Billing Document, Output Type, Invoice Type has been configured for this process and we are doing this without any error. Fyki, we have configured lots of Z Order, Billing & Delivery type to do this processes.
But for one of this order type we need not do any delivery. We want to create Billing Documents from sales order directly (without doing any Outbound Delivery).
So, would u pls advise the steps how can we configure and assign Order Type, Billing Type or any other type to meet above requirement.
Thanks in advance.
Best Regards.
RiponHi
There are two most important configuration:-
1) In VOV8 for your Order Type maintain the Order Related Billing Document
2) Maintain the Copy control setting in VTFA betwwen your Order Type and billing Type.
Also note that if your line item is not require to be delivered then for your Item category maintain (in VOV7) not relevant for delivery and not relevant for scedule line.
Regards
Amitesh Anand
Edited by: Amitesh Anand on May 24, 2010 5:09 PM -
Changing billing document date while creating billing document from vf01
Hi gurus,
I have requirement to change billing doc date while creating billing document from VF01.
here I have to consider goods issue date eq billing date.
caluculating billing date = Goods Issue + Goods in Transit duration time.
I have done everu thing but I cant update the caluculated date, iam using the following enhancement
Enhancement:SDVFX001
Function Module:EXIT_SAPLV60B_001
Include:ZXVVFU01 which are part vf01.
here iam sending the calculated date to VBRK-FKDAT
move cal_date to vbrk-fkdat.
need help how to update the calculated date to VBRK-fkdat i.e billing document date
Regards
BhaskarHi
No! That exit is not good for your issue
U can use the user-exit USEREXIT_NUMBER_RANGE_INV_DATE defined in RV60AFZC
Max -
How to create an invoice from multiple sales doc.
Hi,
how to create an invoice from multiple sales doc.
thanx,
souravhello, friend.
assuming that your settings in VTFA and VTFL allow, you can create 1 invoice for many sales orders or deliveries by using VF04. choose all documents that apply and click "collective billing document".
you can also click on "simulation" if you want to test if the combination is possible and the system will give you a split analysis if this is not possible.
regards. -
Constructing a new Document from External Nodes
Constructing a new Document from External Nodes
I have a situation where:
1. I have an existing XML Document
2. I need to parse for specific Nodes under varying conditions
3. Once the Node is identified -- I would like to append this node as a new Node in a new Document
Is this possible? The methods in the API do not lend themselves to attaching a Node that was not explicitly created by the target Document.Hummm�
That works, sort of; it does allow the node to be imported, but at the Document level only. I will need to apply this at various Node (Element) points, which the API does not permit.
Thanks for the info. -
How to create FI Document in Idoc.....
Hi Abapers,
I hve small doubt that
how to create FI Document in Idoc.....?????s
I was new to the Idoc creation .......
can u give me step by step process..............
Thanks & Regard
Ravi SarmaHi Rahul,
As per my understanding you are loking for creating the IDOC per FI document.
So if in case the multiple rows have retrived from Oracle Join query then Multiple IDOCs to be created. Per row one IDOC.
You can do this just by changing the Occurance of IDOC
Export the XSD structure of imported IDOC from IR and modify the occurance of IDOC field as below example
<xsd:element name="IDOC" type="ZTEST_IDOC.ZIDOC" maxOccurs="unbounded" />
Then Import the xsd file as external defination and use it directly in mapping.
It will create the multiple idocs with mapping Row field of Oracle structure to IDOC field
Thanks
Swarup -
"Create Simple document" from other objects
Scenario: Creating a document using option "Create Simple document" from other objects
I have created a document type and defined the object link for Functional Location with option "create simple document"
When clicking on create icon on the additional data tab on IL02 screen, The system asks for the document type and then the file to be uploaded.
The document type that i have defined has the Description filed as mandatory field and hence i am not able to create the document.
However, for the Document type when i set the description field as not mandatory the system creates DIR. But this DIR has no description.
Please let me know if there is a BADI, using which i could set the Functional location name as the description OR if there is some enhancement by which the user is asked to enter the description when creating the document.
Warm Regards,
Vivek MohankumarHi Vivek,
After my tests I would like to inform you that this is
the standard system behavior as the document description field is
maintained as mandatory in transaction DC10. Please note that for the
simple creation of documents this should not be set as a mandatory
field.
The creation mode can be defined in transaction DC10 for each object
under 'Define object links'.
Please note that the value "1" for the creation of documents is used
to enable a user to simple attache a word file to an object
without going to the transaction CV01n. Therefore the system behaviour
is different then creating a document by CV01n and attaching a
file to it. With simple creation mode there should not be any
mandatory fields as the user cannot enter anything during the creation
process.
However, you can change the behaviour how the document is created by
MM02 transaction if you change the customizing in transaction DC10
like this:
If you maintain the value "2" for creation of documents, the user is
put to transaction CV01n and then the description can be entered. So
maybe this would solve the issue.
Regarding a useful BADI I can only recommned you to test BADI DOCUMENT_OBJ1,
DOCUMENT_OBJ2 or DOCUMENT_MAIN01 for fill the description field.
I hope this information could be useful for you and help to avoid the
mentioned error message.
Best regards,
Christoph -
How to create session id from different string controls
how to create session id from different string controls
fais,
Please create the VI you are talking about and save some default data into all of the controls. Also on the front panel, place the session ID that should be generated by that data. Now, post your VI to a response so I can download it. I can then take this VI and help you create the functionality. (Please post what version of LabVIEW you are using.)
My guess it that you are going to need to use a good number of string concatenations as well as a few string indexes to get parts of strings out. As for the date, you can use a Property node with the Numeric Text.Text property to get the actual string displayed on the front panel for the date and parse out the parts that you want.
Randy Hoskin
Applications Engineer
National Instruments
h
ttp://www.ni.com/ask -
Does any one know how to attach a document from your mail, while you are already in your e-mail, meaning not having to look for your file first and then open the e-mail.
Luis
Good question - and one that a lot of (business) people would like solved!
Your question prompted me to do some research, and I found this workaround posted by Scott Grossberg:
His solution actually addresses a second problem too - how to attach a document when replying to an email message. In your case you may not need to consider the "reply" aspect - but if not right now, it'll come in useful someday!
I've pasted it verbatim - if it works for you (it does for me) then all credit goes to Scott for solving the problem. There's just one thing I'd add to his solution: you will probably want to rename the message, as by default Goodreader gives it the Subject line: Mail with GoodReader attachments.
THE GOODREADER OPTION
1. CREATE the document you want to send.
2. SAVE it to GoodReader (this will require you to buy and install the app).
3. Go to your email and OPEN the email thread to which you want to Reply and attach your file.
4. COMPOSE your Reply.
5. DOUBLE TAP the message.
6. TAP SELECT ALL. This will copy the entire email thread.
7. OPEN GOODREADER on the iPad and go to the file you want to send as part of your Reply.
8. At the bottom of the GoodReader screen you will see an EXPORT icon (it looks like a rectangle with an arrow pointing to the right).
9. TAP the Export button.
10. TAP EMAIL FILE. Depending on your needs, tap either SEND FILE “AS IS” or “FLATTEN ANNOTATIONS.” This will open a compose message screen with the chosen document already attached.
11. TAP in the body of the email screen. TAP PASTE. This will place your composed Reply and the prior email thread into the message.
12. ENTER the Recipients’ names in the TO: field of your message.
13. SEND your email Reply.
The modified version (= when composing a new message rather than a reply):
1 Make sure that the doc you want to attach is saved in GoodReader
2 In the message you are composing, double tap, select all, and then copy.
3 Open GoodReader and select the file you want to attach
4 Select the export button at the bottom of screen
5 Select e-mail file
6 Position cursor in body of the email message, tap and paste. You may want to delete the "sent from GoodReader" text that precedes the attachment.
7 Rename your message (as by default it will be Mail with GoodReader attachments)
8 Add the recipient's address in the To field.
Hope this helps! All thanks to Scott for this workaround. -
How do I retrieve documents from my iCloud that i made in pages
How do I retrieve documents from my iCloud that i made in pages
Welcome to the Apple community.
Your question is a little unclear, however if you mean how can you retrieve documents you have created on your iOS device on your Mac, then you need to download them at iCloud.com using the web browser (Safari or similar) on your mac. -
Change in document type while creating billing document from sales order
While creating billing document from Sales order it is creating with document type RV which is standerd one but i want to change Document type.
How can i change it?
Regards
RajHi
If you use another existing document type, check that it has a number range suitable to you. Else create a new 'z' type and assign an entirely new number range, not used in the other doc types.
It is useful to make the FI document number the same number. If I understand from the forums, the FI number range must be external. Search the forum for this. It is very useful for the Finance people.
Kind regards
Dawn
Edited by: Dawn Verrell on Sep 9, 2010 4:10 PM
Maybe you are looking for
-
Logitech webcam no longer works on 10.8.5.
My c615 logitech webcam stopped working on my mac mini when I updated to 10.8.5. Logitech says it is a mac problem. Any help would be appreciated.
-
Error "4" when trying to test my connection
Hi, please help me find out how to fix this error: when i try to test the connection pops up an error message with only a number "4" in it, nothing else. what's this error message about and how do i fix it?? Thanx in advance!!!
-
How do I save documents in 2009 Pages for my new IMac
I have a new 10.10.2 iMac and cannot open saved documents from older version of pages. Is there a way to convert them?
-
How do I send an iphoto slide show with music via email?
-
Users in "Trial" mode when we have an Enterprise license
My users are recieving a message about "Trial mode". These users have CC ENTERPRISE installed have limited access to applications, showing "Try" rather than "Install", their membership shows that they are in "Trial mode". The package was created with