Newbie - create xml to string
I'm new to JAXP. I just want to use JAXP to create a DOM, then get the XML to use as a String in Java without any directives. Just a simple as possible like :
<myelement>
<myprop name="myname"/>
</myelement>
Is there some simple code I can use to do this? It can create the simple DOM using the code below, but how to I get the String value?
javax.xml.parsers.DocumentBuilderFactory dfactory =
javax.xml.parsers.DocumentBuilderFactory.newInstance();
Node top = doc.createElement("myelement");
top.appendChild(doc.createTextNode("child"));
doc.appendChild(top);
Thanks!
Use a Transformer with a null xsl, and specify the target as a StringWriter
Similar Messages
-
How do I create XML output as string without the ?xml ? tag
I need to create xml from a database query result. I am able to do this but it includes the <?xml ?> header tag. I need to create the xml without the header tag <?xml ?>. Please advise.
Here is my source:
package sql_test;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.*;
import javax.xml.transform.stream.*;
import javax.xml.transform.dom.*;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import java.sql.*;
public class SQLConnector {
java.sql.Connection conn;
public SQLConnector()
conn = null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection("jdbc:mysql://localhost/test", "admin", "admin");
} catch(Exception e) {
System.err.println("Exception: " + e.getMessage());
public String getTestData()
Document doc = null;
Statement s = null;
ResultSet rs = null;
String str = null;
try {
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
doc = builder.newDocument();
Element results = doc.createElement("Results");
doc.appendChild(results);
s = conn.createStatement();
s.executeQuery("select * from test_table");
rs = s.getResultSet ();
ResultSetMetaData rsmd = rs.getMetaData();
int colCount = rsmd.getColumnCount();
while (rs.next()) {
Element row = doc.createElement("Row");
results.appendChild(row);
for (int ii = 1; ii <= colCount; ii++) {
String columnName = rsmd.getColumnName(ii);
Object value = rs.getObject(ii);
Element node = doc.createElement(columnName);
node.appendChild(doc.createTextNode(value.toString()));
row.appendChild(node);
str = getDocumentAsXml(doc);
catch (Exception e) {
e.printStackTrace();
finally {
try {
if (conn != null) conn.close();
if (s != null) s.close();
if (rs != null) rs.close();
catch (Exception e) {
return str;
public static String getDocumentAsXml(Document doc) throws TransformerConfigurationException, TransformerException
DOMSource domSource = new DOMSource(doc);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
java.io.StringWriter sw = new java.io.StringWriter();
StreamResult sr = new StreamResult(sw);
transformer.transform(domSource, sr);
return sw.toString();
}OutputKeys.OMIT_XML_DECLARATION
-
Creating a Function module to send XML Byte String
Hi all,
I have to create a Function module to get XML byte string.The internal table is dynamic coloums based on how many data selected as a importparameter.from the internal; table data I have to create a XML byte string as a output.Pl help me to proceed further.
Thanks in Advance.
RamIf i have your question right you need to convert an internal table of unknown type to an xml string then to a byte string.
data xmlString type string.
data xmlXString type xstring.
call transformation id
source
table = internalTableYouWantToExport
result
xml xmlString.
export xmlString to data buffer xmlXString.
xmlString has the xml of the table and xmlXString contains the byte representation of the string. -
Newbie - How to create XML based on given schema
Hello,
We have a requirement to create an XML message from our system (Oracle 9iR2 with Oracle Apps 11.5.10). The XML is generated from a query in our HR tables, and must be in a specific format (schema and example XML has been provided to us).
Newbie question is this: What is the best way to create this XML message (dynamic data coming from a SQL select) while ensuring that it matches the given schema? Most of our developers are strong PL/SQL with limited Java experience.
Thanks,
-- JohnI've updated the FAQ with an answer and example for this question...
Please see the following thread
How to create XML from relational tables based on an XML Schema ? -
Newbie: Problem populating DataGrid from CF created xml
Hi,
I'm new to Flex and I'm working my way through the chapter 'Using HTTPService components' so I can populate a DataGrid from CF created xml.
The Document on Live docs works only partially for me - ColdFusion section under (http://livedocs.adobe.com/flex/3/html/help.html?content=data_access_2.html#195458).
The insert part works and I'm able to write to the database without a problem, but the DataGrid is not being populated and stays empty? I'm working locally, so there shouldn't be any cross-domain issue?
Hope someone is able to point into the right direction.
Thanks.Use the debugger and see if any data is received from the server on request ( I'm assuming that somewhere, you are making a request to the server that should read some data ). If data is received then you are not populating the DataGrid correctly ( most likely you are not giving the correct path to the elements that should appear in the DataGrid ); else, the server-side script is not reading any data and you should check why.
-
MapViewer API: addMapCacheTheme creates unexpected XML request string
Hi,
I try to get a map with map cache theme on it. But MapViewer class generates an xml request string in which an unexpected wfs theme
exists. So I'm unable to add a map cache theme since the wfs theme causes a problem and i only get an image painted with background
color...
my java code is as follows:
String viewerUrl = "http://localhost:8888/mapviewer/omserver";
String dataSource = "ADATASOURCE";
String mapCache= "AMAPCACHE";
MapViewer viewer = new MapViewer(viewerUrl);
viewer.setDataSourceName(dataSource);
viewer.setImageFormat(MapViewer.FORMAT_PNG_URL);
viewer.setMapRequestSRID(8307);
viewer.setAntiAliasing(false);
viewer.setMapTitle(null);
viewer.setBackgroundColor(new Color(0xA6CAF0));
viewer.setBackgroundImageURL(null);
viewer.setDeviceSize(new Dimension(480, 480));
//viewer.setBaseMapName(baseMap);
viewer.addMapCacheTheme(mapCache, dataSource, mapCache, true);
viewer.setCenter(29, 41);
viewer.setSize(1);
//For debugging issues
String req = viewer.getMapRequestString();
viewer.run();
value for req variable is:
<?xml version="1.0" standalone="yes"?>
<map_request
datasource="ADATASOURCE"
srid="8307"
width="480"
height="480"
bgcolor="#a6caf0"
antialiase="false"
format="PNG_URL"
>
<center size="1.0">
<geoFeature>
<geometricProperty typeName="center">
<Point>
<coordinates>29.0,41.0</coordinates>
</Point>
</geometricProperty>
</geoFeature>
</center>
<themes>
<theme name="AMAPCACHE" datasource="ADATASOURCE">
<map_cache_theme map_cache_name="AMAPCACHE" snap_to_cache_scale="true"/> </theme> <theme name="AMAPCACHE" >
<wfs_feature_request
datasource="ADATASOURCE"
/>
</theme>
</themes>
</map_request>
The first theme is the one that i wanted to add.
The second one (bold) is the one that causes trouble. I don't know where it comes from.
This problem occured when i started to use mvclient.jar that came with patch 6453515 which changed MapViewer version from
Ver10131_B06102 to Ver11_B07100.
The old mvclient.jar (came with MapViewer Ver10131_B06102) produces the following xml request string:
<?xml version="1.0" standalone="yes"?>
<map_request
datasource="ADATASOURCE"
srid="8307"
width="480"
height="480"
bgcolor="#a6caf0"
antialiase="false"
format="PNG_URL"
>
<center size="1.0">
<geoFeature>
<geometricProperty typeName="center">
<Point>
<coordinates>29.0,41.0</coordinates>
</Point>
</geometricProperty>
</geoFeature>
</center>
<themes>
<theme name="AMAPCACHE" datasource="ADATASOURCE">
<map_cache_theme map_cache_name="AMAPCACHE" snap_to_cache_scale="true"/> </theme> </themes>
</map_request>
What might cause this problem?
OS: Windows XP Pro SP2
IDE: JDeveloper 10.1.3.1.0
Thanks in advance,
CihanHi Cihan,
it is confirmed to be a bug with this client library and it will be fixed. Thanks.
Joao -
How to create xml file through SDK?
Hi,
I need help in creating the xml file using SAP B1 SDK?
i want to create xml file which is in tally xml format.
Warm Ragards,
MahendraHi Mahendra,
This is an example to save a form as XML :
try
System.Xml.XmlDocument oXmlDoc = null;
string sXmlString = null;
oXmlDoc = new System.Xml.XmlDocument();
// get the form as an XML string
sXmlString = Form.GetAsXML();
// load the form's XML string to the
// XML document object
oXmlDoc.LoadXml(sXmlString);
string sPath = null;
sPath = System.IO.Directory.GetParent(System.Windows.Forms.Application.StartupPath).ToString();
sPath = System.IO.Directory.GetParent(sPath).ToString();
// save the XML Document
oXmlDoc.Save((sPath + @"\Form" + sType + ".xml"));
//oXmlDoc.Save(DIRECTORY_TEMPLATE + "Form" + sType + ".xml");
catch (Exception ex)
SBO_Application.MessageBox("ERROR in 'SaveAsXML()' : " + ex.Message, 1, "Ok", "", "");
And an example to navigate in the XML file :
System.Xml.XmlDocument xxml;
System.Xml.XmlNode node;
System.Xml.XmlNodeList nodes;
xxml = new System.Xml.XmlDocument();
xxml.LoadXml(oRecAU.GetAsXML());
nodes = xxml.SelectNodes("BOM/BO/IFC_AU/row");
foreach (System.Xml.XmlNode node in nodes)
oColumn.ValidValues.Add(node.SelectSingleNode("Code").InnerText, node.SelectSingleNode("Name").InnerText);
I hope it's help you.
Regards
Michael -
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 -
Creating XML File Using xmldom Package
How can I create an XML file from scratch using the PL/SQL xmldom package?
I want to create an XML file using the xmldom package instead of building the individual tags as strings of VARCHAR2 character data. There is quite a bit of documentation regarding manipulating input XML files using DOM -- but not for creating XML files from scratch given known "tagnames" (<lastName>) and retrieved database "values" ("Smith").
<person>
<lastName>Smith</lastName>
</person>
Is there any documentation that you can recommend?
Thank you.Here is an example.
The create_file procedure creates the file.
The other procedures are generic procs that can be used with any XML.
PROCEDURE create_file_with_root(po_xmldoc OUT xmldom.DOMDocument,
pi_root_tag IN VARCHAR2,
po_root_element OUT xmldom.domelement,
po_root_node OUT xmldom.domnode,
pi_doctype_url IN VARCHAR2) IS
xmldoc xmldom.DOMDocument;
root xmldom.domnode;
root_node xmldom.domnode;
root_element xmldom.domelement;
record_node xmldom.domnode;
newelenode xmldom.DOMNode;
BEGIN
xmldoc := xmldom.newDOMDocument;
xmldom.setVersion(xmldoc, '1.0');
xmldom.setDoctype(xmldoc, pi_root_tag, pi_doctype_url,'');
-- Create the root --
root := xmldom.makeNode(xmldoc);
-- Create the root element in the file --
create_element_and_append(xmldoc, pi_root_tag, root, root_element, root_node);
po_xmldoc := xmldoc;
po_root_node := root_node;
po_root_element := root_element;
END create_file_with_root;
PROCEDURE create_element_and_append(pi_xmldoc IN OUT xmldom.DOMDocument,
pi_element_name IN VARCHAR2,
pi_parent_node IN xmldom.domnode,
po_new_element OUT xmldom.domelement,
po_new_node OUT xmldom.domnode) IS
element xmldom.domelement;
child_node xmldom.domnode;
newelenode xmldom.DOMNode;
BEGIN
element := xmldom.createElement(pi_xmldoc, pi_element_name);
child_node := xmldom.makeNode(element);
-- Append the new node to the parent --
newelenode := xmldom.appendchild(pi_parent_node, child_node);
po_new_node := child_node;
po_new_element := element;
END create_element_and_append;
FUNCTION create_text_element(pio_xmldoc IN OUT xmldom.DOMDocument, pi_element_name IN VARCHAR2,
pi_element_data IN VARCHAR2, pi_parent_node IN xmldom.domnode) RETURN xmldom.domnode IS
parent_node xmldom.domnode;
child_node xmldom.domnode;
child_element xmldom.domelement;
newelenode xmldom.DOMNode;
textele xmldom.DOMText;
compnode xmldom.DOMNode;
BEGIN
create_element_and_append(pio_xmldoc, pi_element_name, pi_parent_node, child_element, child_node);
parent_node := child_node;
-- Create a text node --
textele := xmldom.createTextNode(pio_xmldoc, pi_element_data);
child_node := xmldom.makeNode(textele);
-- Link the text node to the new node --
compnode := xmldom.appendChild(parent_node, child_node);
RETURN newelenode;
END create_text_element;
PROCEDURE create_file IS
xmldoc xmldom.DOMDocument;
root_node xmldom.domnode;
xml_doctype xmldom.DOMDocumentType;
root_element xmldom.domelement;
record_element xmldom.domelement;
record_node xmldom.domnode;
parent_node xmldom.domnode;
child_node xmldom.domnode;
newelenode xmldom.DOMNode;
textele xmldom.DOMText;
compnode xmldom.DOMNode;
BEGIN
xmldoc := xmldom.newDOMDocument;
xmldom.setVersion(xmldoc, '1.0');
create_file_with_root(xmldoc, 'root', root_element, root_node, 'test.dtd');
xmldom.setAttribute(root_element, 'interface_type', 'EXCHANGE_RATES');
-- Create the record element in the file --
create_element_and_append(xmldoc, 'record', root_node, record_element, record_node);
parent_node := create_text_element(xmldoc, 'title', 'Mr', record_node);
parent_node := create_text_element(xmldoc, 'name', 'Joe', record_node);
parent_node := create_text_element(xmldoc,'surname', 'Blogs', record_node);
-- Create the record element in the file --
create_element_and_append(xmldoc, 'record', root_node, record_element, record_node);
parent_node := create_text_element(xmldoc, 'title', 'Mrs', record_node);
parent_node := create_text_element(xmldoc, 'name', 'A', record_node);
parent_node := create_text_element(xmldoc, 'surname', 'B', record_node);
-- write the newly created dom document into the buffer assuming it is less than 32K
xmldom.writeTofile(xmldoc, 'c:\laiki\willow_data\test.xml');
EXCEPTION
WHEN xmldom.INDEX_SIZE_ERR THEN
RAISE_APPLICATION_ERROR(-20120, 'Index Size error');
WHEN xmldom.DOMSTRING_SIZE_ERR THEN
RAISE_APPLICATION_ERROR(-20120, 'String Size error');
WHEN xmldom.HIERARCHY_REQUEST_ERR THEN
RAISE_APPLICATION_ERROR(-20120, 'Hierarchy request error');
WHEN xmldom.WRONG_DOCUMENT_ERR THEN
RAISE_APPLICATION_ERROR(-20120, 'Wrong doc error');
WHEN xmldom.INVALID_CHARACTER_ERR THEN
RAISE_APPLICATION_ERROR(-20120, 'Invalid Char error');
WHEN xmldom.NO_DATA_ALLOWED_ERR THEN
RAISE_APPLICATION_ERROR(-20120, 'Nod data allowed error');
WHEN xmldom.NO_MODIFICATION_ALLOWED_ERR THEN
RAISE_APPLICATION_ERROR(-20120, 'No mod allowed error');
WHEN xmldom.NOT_FOUND_ERR THEN
RAISE_APPLICATION_ERROR(-20120, 'Not found error');
WHEN xmldom.NOT_SUPPORTED_ERR THEN
RAISE_APPLICATION_ERROR(-20120, 'Not supported error');
WHEN xmldom.INUSE_ATTRIBUTE_ERR THEN
RAISE_APPLICATION_ERROR(-20120, 'In use attr error');
WHEN OTHERS THEN
dbms_output.put_line('exception occured' || SQLCODE || SUBSTR(SQLERRM, 1, 100));
END create_file; -
/* Style Definitions */
table.MsoNormalTable
{mso-style-name:"Table Normal";
mso-tstyle-rowband-size:0;
mso-tstyle-colband-size:0;
mso-style-noshow:yes;
mso-style-priority:99;
mso-style-qformat:yes;
mso-style-parent:"";
mso-padding-alt:0in 5.4pt 0in 5.4pt;
mso-para-margin:0in;
mso-para-margin-bottom:.0001pt;
mso-pagination:widow-orphan;
font-size:11.0pt;
font-family:"Calibri","sans-serif";
mso-ascii-font-family:Calibri;
mso-ascii-theme-font:minor-latin;
mso-fareast-font-family:"Times New Roman";
mso-fareast-theme-font:minor-fareast;
mso-hansi-font-family:Calibri;
mso-hansi-theme-font:minor-latin;
mso-bidi-font-family:"Times New Roman";
mso-bidi-theme-font:minor-bidi;}
For the last 5 years (and in IPCC3.x/4.x,UCCX/5.x/7.x) I've used the same basic subflow to read a XML document that contains holiday dates where the queue should be closed. I've re-used this script on 20+ client installs and it's always worked. The structure of the script allows you to pass the path and filename of the XML document as parameters to the subflow. (The document is in the repository)
I loaded this script in UCCX 8.0.2 recently and it crashed with a Java.IO error. It looked like it was trying to read the file system directly and not the repository. (In the Linux appliance model this kind of makes sense but why is the step trying to read the file system directly?)
So I open a TAC case (SR# 615243125) and TAC tells me that the method of using the Create File Document step is not supported anymore and that I should specify the filename directly in the Create XML Document step
The problem that I see (aside from having to edit all my scripts that use XML files) is that the Create XML Document step is looking for the input to be a type DOCUMENT and not a type STRING. This seems to imply that I have to hardcode the document in each script that I deploy for a customer. When it was a string it was easy to construct the full file path from parameters and pass to the subflow.
Questions to the group
#1 Am I missing something here?
#2 Do you assume that you'll be able to load a script that worked fine in UCCX 7 into UCCX 8 and that it should completely function when you're doing everything according to the step reference documentation.
#3 Cisco didn’t document this in any way that I can find.
#4 How can you use the Create XML Document step in a fashion that would let you construct the path of the file and the filename previously in the script so you could pass it to a subflow ? It would seem this functionality has been killed in UCCX 8
/* Style Definitions */
table.MsoNormalTable
{mso-style-name:"Table Normal";
mso-tstyle-rowband-size:0;
mso-tstyle-colband-size:0;
mso-style-noshow:yes;
mso-style-priority:99;
mso-style-qformat:yes;
mso-style-parent:"";
mso-padding-alt:0in 5.4pt 0in 5.4pt;
mso-para-margin:0in;
mso-para-margin-bottom:.0001pt;
mso-pagination:widow-orphan;
font-size:11.0pt;
font-family:"Calibri","sans-serif";
mso-ascii-font-family:Calibri;
mso-ascii-theme-font:minor-latin;
mso-fareast-font-family:"Times New Roman";
mso-fareast-theme-font:minor-fareast;
mso-hansi-font-family:Calibri;
mso-hansi-theme-font:minor-latin;
mso-bidi-font-family:"Times New Roman";
mso-bidi-theme-font:minor-bidi;}
(Background)
Create File Document Step
The input filename is a STRING, could be an explicit path and filename in the repository or a variable that represents that path and string
The output of this step is a DOCUMENT to be used in the Create XML Document step
The string FILE_FullPathHolidayFiles references en_us\folderName\documentName.xml
The document was properly uploaded into the repository only, NOT trying to directly read c:\foo\blah…
/* Style Definitions */
table.MsoNormalTable
{mso-style-name:"Table Normal";
mso-tstyle-rowband-size:0;
mso-tstyle-colband-size:0;
mso-style-noshow:yes;
mso-style-priority:99;
mso-style-qformat:yes;
mso-style-parent:"";
mso-padding-alt:0in 5.4pt 0in 5.4pt;
mso-para-margin:0in;
mso-para-margin-bottom:.0001pt;
mso-pagination:widow-orphan;
font-size:11.0pt;
font-family:"Calibri","sans-serif";
mso-ascii-font-family:Calibri;
mso-ascii-theme-font:minor-latin;
mso-fareast-font-family:"Times New Roman";
mso-fareast-theme-font:minor-fareast;
mso-hansi-font-family:Calibri;
mso-hansi-theme-font:minor-latin;
mso-bidi-font-family:"Times New Roman";
mso-bidi-theme-font:minor-bidi;}
The create XML document input can only be a type DOCUMENT#1 Am I missing something here?
You are mixing two different issues together here.
The Create File Document step is indeed not needed or supported for creating an XML document. That is why there is a unique step; to trigger XML parsing within the MIVR subsystem.
Accessing the file system is restricted to a single folder within the VOS model (i.e. 8.0+). This folder is not backed up, replicated, or cleaned up automatically. It was intended to give developers some FS access as a temporary swap location only.
#2 Do you assume that you'll be able to load a script that
worked fine in UCCX 7 into UCCX 8 and that it should completely
function when you're doing everything according to the step reference
documentation.
Assume nothing; read the documentation and attend one of the dozens of partner training sessions that CCBU put on advising of the upcoming changes.
#3 Cisco didn’t document this in any way that I can find.
You're right, I guess, on the Create File vs. XML Document step. AFAIK Cisco never wrote a notice into the Step Reference Guide explicitly stating that you cannot use the Create File Document although the documentation seemed pretty clear to me without it. File system restrictions are documented in the 8.0 release notes.
Scripting and Development Series: Volume 2, Editor Step ReferenceUse the Create XML Document step to create a logical document that maps a document to another document variable (where the document has already been pre-parsed as an XML document and is ready to be accessed by the Get XML Document Data step).Use this step before the Get XML Document Data step to obtain data from a document formatted using the Extensible Markup Language (XML).
#4 How can you use the Create XML Document step in a fashion that would
let you construct the path of the file and the filename previously in
the script so you could pass it to a subflow ? It would seem this functionality has been killed in UCCX 8
No it hasn't; just concatinate a string to build the Source Document parameter the step needs. Example: "DOC[" + myFilePath + "]" -
Create XML Element Tag BasedOn Found Character Style
Hi,
Good Day!
Basically I want to search only for character styles that contains "ntb-", that is why it is hard coded in my searchString variable.
Although I was able to create XML tag based on selected character style, but it will always add/insert at the end of the parent XML element.
Can anyone could help me how insert/add that element at the insertion point where the text is found?
Thanks,
--elmer
var myDoc = app.documents[0];
myDoc.viewPreferences.horizontalMeasurementUnits = MeasurementUnits.POINTS;
myDoc.viewPreferences.verticalMeasurementUnits = MeasurementUnits.POINTS;
var charStyles = myDoc.allCharacterStyles;
var foundStyles = Array();
var searchString = String();
searchString = 'ntb-';
var tempName = String();
var tempName1 = String();
for(var i = 1; charStyles.length > i; i++){
tempName = charStyles[i].name;
tempName1 = tempName.toLowerCase();
if(tempName1.indexOf (searchString.toLowerCase()) != -1){
foundStyles.push (tempName);
var myDialog = app.dialogs.add({name: "Convert Footnote Character Styles to XML Tags",canCancel:true});
with (myDialog) {
with (dialogColumns.add().borderPanels.add()) {
with (dialogColumns.add()) {
staticTexts.add({staticLabel: "Character style to search : "}); }
with (dialogColumns.add()) {
selCharStyle = dropdowns.add({stringList: foundStyles, selectedIndex: 0, minWidth: 175});
var dialogShown = myDialog.show();
while (dialogShown) {
if (selCharStyle.selectedIndex == 0) {
alert("Must have at least a character style to search!");
dialogShown = myDialog.show();
continue;
} else {
insertXMLTags(selCharStyle.stringList[selCharStyle.selectedIndex], selCharStyle.selectedIndex, "0");
break;
myDialog.destroy();
alert("Finished!");
exit();
function insertXMLTags(cStyle, cStyleIndex, ip) {
var myFinds = searchStyle(cStyle, cStyleIndex);
for (i=myFinds.length - 1; i>=0; i--) {
var myIP = myFinds[i].texts.item(0).insertionPoints.item(0);
var myParentXML = myIP.associatedXMLElements[0];
var myChiidXML = myParentXML.xmlElements.add ( cStyle );
myChiidXML.contents = myFinds[i].contents;
//set the selection
app.selection = myFinds[i].texts.item(0);
//remove the selected text
myFinds[i].texts.item(0).remove();
Utility Functions
function searchStyle(cStyle, cStyleIndex){
var myFinds;
// if script version is for Indesign CS2
if (app.scriptPreferences.version < 5){
app.findPreferences = NothingEnum.nothing;
app.changePreferences = NothingEnum.nothing;
myFinds = myDoc.search(undefined, undefined, undefined, undefined,
{appliedParagraphStyle: pStyle, appliedCharacterStyle: cStyle});
// else, for CS3 and CS4
}else{
//Clear any existing find/change settings
app.findTextPreferences = NothingEnum.nothing;
app.changeTextPreferences = NothingEnum.nothing;
// set character or paragraph style to search
if (cStyleIndex != 0){
app.findTextPreferences.appliedCharacterStyle = cStyle;
//Set the find options.
app.findChangeTextOptions.caseSensitive = false;
app.findChangeTextOptions.includeFootnotes = true;
app.findChangeTextOptions.includeHiddenLayers = false;
app.findChangeTextOptions.includeLockedLayersForFind = false;
app.findChangeTextOptions.includeLockedStoriesForFind = false;
app.findChangeTextOptions.includeMasterPages = false;
app.findChangeTextOptions.wholeWord = false;
myFinds = myDoc.findText();
return myFinds;Here is a way you can find any field.
Download the current template.
Open it in word and go to the line that you are interested in.
The blanket PO# will be a field. Right click on it and go to properties. You will see the xml element there.
Hope this answers your question,
Sandeep Gandhi -
How to Create XML Schema From JTree ?
Please help me... Thank you.
This is Code
Tree.java ----- Run This File
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.tree.DefaultMutableTreeNode;
public class Tree extends JPanel implements ActionListener {
private int newNodeSuffix = 1;
private static String ADD_COMMAND = "add";
private static String REMOVE_COMMAND = "remove";
private static String CLEAR_COMMAND = "clear";
private static String OK_COMMAND = "ok";
private DynamicTree treePanel;
public Tree() {
super(new BorderLayout());
//Create the components.
treePanel = new DynamicTree();
//populateTree(treePanel);
JButton addButton = new JButton("Add");
addButton.setActionCommand(ADD_COMMAND);
addButton.addActionListener(this);
JButton removeButton = new JButton("Remove");
removeButton.setActionCommand(REMOVE_COMMAND);
removeButton.addActionListener(this);
JButton clearButton = new JButton("Clear");
clearButton.setActionCommand(CLEAR_COMMAND);
clearButton.addActionListener(this);
JButton okButton = new JButton("OK");
okButton.setActionCommand(OK_COMMAND);
okButton.addActionListener(this);
//Lay everything out.
treePanel.setPreferredSize(new Dimension(300, 150));
add(treePanel, BorderLayout.CENTER);
JPanel panel = new JPanel(new GridLayout(0,1));
panel.add(addButton);
panel.add(removeButton);
panel.add(clearButton);
panel.add(okButton);
add(panel, BorderLayout.LINE_END);
/*public void populateTree(DynamicTree treePanel) {
String p1Name = new String("Parent 1");
//String p2Name = new String("Parent 2");
String c1Name = new String("Child 1");
//String c2Name = new String("Child 2");
DefaultMutableTreeNode p1;
p1 = treePanel.addObject(null, p1Name);
//p2 = treePanel.addObject(null, p2Name);
treePanel.addObject(p1, c1Name);
//treePanel.addObject(p1, c2Name);
//treePanel.addObject(p2, c1Name);
//treePanel.addObject(p2, c2Name);
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (ADD_COMMAND.equals(command)) {
//Add button clicked.
treePanel.addObject("New Node " + newNodeSuffix++);
} else if (REMOVE_COMMAND.equals(command)) {
//Remove button clicked.
treePanel.removeCurrentNode();
} else if (CLEAR_COMMAND.equals(command)) {
//Clear button clicked.
treePanel.clear();
} else if (OK_COMMAND.equals(command)) {
//Ok button clicked.
treePanel.ok();
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("Craete XML Tree");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
Tree newContentPane = new Tree();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
frame.setVisible(true);
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}DynamicTree.java
import javax.swing.JOptionPane;
import java.awt.GridLayout;
import java.awt.Toolkit;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.MutableTreeNode;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;
import javax.swing.event.TreeModelEvent;
import javax.swing.event.TreeModelListener;
public class DynamicTree extends JPanel {
protected DefaultMutableTreeNode rootNode;
protected DefaultTreeModel treeModel;
protected JTree tree;
private Toolkit toolkit = Toolkit.getDefaultToolkit();
public DynamicTree() {
super(new GridLayout(1,0));
rootNode = new DefaultMutableTreeNode("Root Node");
treeModel = new DefaultTreeModel(rootNode);
treeModel.addTreeModelListener(new MyTreeModelListener());
tree = new JTree(treeModel);
tree.setEditable(true);
tree.getSelectionModel().setSelectionMode
(TreeSelectionModel.SINGLE_TREE_SELECTION);
tree.setShowsRootHandles(true);
JScrollPane scrollPane = new JScrollPane(tree);
add(scrollPane);
/** Remove all nodes except the root node. */
public void clear() {
rootNode.removeAllChildren();
treeModel.reload();
public void ok() {
int n = JOptionPane.showConfirmDialog(null, "Do you want to create XML Schema?", "", JOptionPane.YES_NO_OPTION);
/** Remove the currently selected node. */
public void removeCurrentNode() {
TreePath currentSelection = tree.getSelectionPath();
if (currentSelection != null) {
DefaultMutableTreeNode currentNode = (DefaultMutableTreeNode)
(currentSelection.getLastPathComponent());
MutableTreeNode parent = (MutableTreeNode)(currentNode.getParent());
if (parent != null) {
treeModel.removeNodeFromParent(currentNode);
return;
// Either there was no selection, or the root was selected.
toolkit.beep();
/** Add child to the currently selected node. */
public DefaultMutableTreeNode addObject(Object child) {
DefaultMutableTreeNode parentNode = null;
TreePath parentPath = tree.getSelectionPath();
if (parentPath == null) {
parentNode = rootNode;
} else {
parentNode = (DefaultMutableTreeNode)
(parentPath.getLastPathComponent());
return addObject(parentNode, child, true);
public DefaultMutableTreeNode addObject(DefaultMutableTreeNode parent,
Object child) {
return addObject(parent, child, false);
public DefaultMutableTreeNode addObject(DefaultMutableTreeNode parent,
Object child,
boolean shouldBeVisible) {
DefaultMutableTreeNode childNode =
new DefaultMutableTreeNode(child);
if (parent == null) {
parent = rootNode;
treeModel.insertNodeInto(childNode, parent,
parent.getChildCount());
//Make sure the user can see the lovely new node.
if (shouldBeVisible) {
tree.scrollPathToVisible(new TreePath(childNode.getPath()));
return childNode;
class MyTreeModelListener implements TreeModelListener {
public void treeNodesChanged(TreeModelEvent e) {
DefaultMutableTreeNode node;
node = (DefaultMutableTreeNode)
(e.getTreePath().getLastPathComponent());
* If the event lists children, then the changed
* node is the child of the node we've already
* gotten. Otherwise, the changed node and the
* specified node are the same.
try {
int index = e.getChildIndices()[0];
node = (DefaultMutableTreeNode)
(node.getChildAt(index));
} catch (NullPointerException exc) {}
System.out.println("The user has finished editing the node.");
System.out.println("New value: " + node.getUserObject());
public void treeNodesInserted(TreeModelEvent e) {
public void treeNodesRemoved(TreeModelEvent e) {
public void treeStructureChanged(TreeModelEvent e) {
}XML shema is basically an XML file. So u need to know how to create an XML,
provided u know how the shema file should be.
Creating an XML :
http://forum.java.sun.com/thread.jspa?threadID=5181031&messageID=9705786#9705786 -
XML Input String too long to Test Web Service in App Server
We have a Web Service that accepts an XML input string but when we deploy this web service and try to test it through the Application Server it errors out because the input string is too long. Is there any way around this??
Thanks...Update:
Now I see that there are in fact two error messages. The second one is the one presented above. But the first one says:
Line: 145
Char: 97
Error: Expected ';'
Code: 0
My question now is to what file it is referring?? Is it to ProjectAccountingPort.js that is automatically created? THen why is it not properly created??
Please, please help me with this! The deadline is in a few days... -
Passing xml as string to xmlPanel function
hello Genius,
I am using XML2UI feature of Extending Flash. I want to pass
XML through string in place of xml file in xmlPanel function.
is there any way to avoid creating 20 xml files and
distributing them as my planned extension have 20 ui's.
thanks in advance.Hai Shyam,
I have tried to do as u have mentioned but still its not taking it as a paramater.
i mean the API say
parse
public void parse(InputSource input) throws IOException,
SAXExceptionParse an XML document.
The application can use this method to instruct the XML reader to begin parsing an XML document from any valid input source (a character stream, a byte stream, or a URI).
Is is any way to convert string to (char stream or byte stream).
Thanks a lot
Pooja. -
Error in tutorial: Could not create XML document carrying AQ Headers
Hi,
We try to run the AQOutboundCorrelation tutorial. After running the enqueue_reply.sql script the message was placed from the request to the reply queue and read by the AQ inbound adapter.
Nothing happened in the flow. The following error occured in the domain log:
Could not create XML document carrying AQ Headers
Please help!!
See log messages below
<2007-01-18 13:58:59,187> <DEBUG> <default.collaxa.cube.activation> <AQ Adapter::Inbound> MessageReader_addPrimitive: field = PAYLOAD, value = Hallo
<2007-01-18 13:58:59,187> <DEBUG> <default.collaxa.cube.activation> <AQ Adapter::Inbound> MessageReader_addPrimitive: field = RESULT, value = request received
<2007-01-18 13:58:59,187> <DEBUG> <default.collaxa.cube.activation> <AQ Adapter::Inbound> MessageReader_getAsXML message:<<<<<<<
<?xml version = '1.0' standalone = 'yes'?>
<CORRELATIONREPLY_TYPE xmlns="http://xmlns.oracle.com/xdb/ANDRE">
<PAYLOAD xmlns="">Hallo</PAYLOAD>
<RESULT xmlns="">request received</RESULT>
</CORRELATIONREPLY_TYPE>
>>>>>>>>
<2007-01-18 13:58:59,187> <DEBUG> <default.collaxa.cube.activation> <AQ Adapter::Inbound> MessageReader_readMessage: aqHeader = oracle.xml.parser.v2.XMLDocument@eabad
<2007-01-18 13:58:59,187> <DEBUG> <default.collaxa.cube.activation> <AQ Adapter::Inbound> MessageReader_readMessage:Header<<<<<<<
<?xml version = '1.0' standalone = 'yes'?>
<Header xmlns="http://xmlns.oracle.com/pcbpel/adapter/aq/inbound/">
<MessageId>CA714367FA1B4BB3B2AC0211C9ECF2DB</MessageId>
<Priority>1</Priority>
<Correlation>209EE57CB6AC4B2FA2034C6FA58AD24B</Correlation>
<Attempts>0</Attempts>
<EnqueueTime>2007-01-18T13:58:59.000+01:00</EnqueueTime>
<OrigMessageId></OrigMessageId>
</Header>
>>>>>>>>
<2007-01-18 13:58:59,187> <ERROR> <default.collaxa.cube.activation> <AQ Adapter::Inbound> MessageReader_ReadMessage: Could not create XML document carrying AQ Headers: [Ljava.lang.StackTraceElement;@12916fe
<2007-01-18 13:58:59,187> <ERROR> <default.collaxa.cube.activation> <AQ Adapter::Inbound>
java.lang.NullPointerException
at java.lang.String.<init>(String.java:479)
at oracle.tip.adapter.aq.database.MessageReader.readMessage(MessageReader.java:573)
at oracle.tip.adapter.aq.inbound.AQActivationSpecDequeuer.run(AQActivationSpecDequeuer.java:183)
at oracle.tip.adapter.fw.jca.work.WorkerJob.go(WorkerJob.java:51)
at oracle.tip.adapter.fw.common.ThreadPool.run(ThreadPool.java:272)
at java.lang.Thread.run(Thread.java:595)
Message was edited by:
rverbeea1Sorry for not mentioning the product versions:
The bpel process was build and deployed with Jdeveloper Studio edition version 10.1.3.1.0.3984 on a Bpel server/Application Server with version 10.1.3.1 (NT).
Maybe you are looking for
-
My songs are still on my ipod but they wont play
So my playlist is still on my ipod and when i choose a song it displays the title and artist, but the song itelf wont play. anything i can do?
-
Problems using iPhoto via Screen Sharing
To deal with our family's ever-growing photo library, I bought a new Mac Mini with a jumbo hard drive. For now, I want to run this as a headless server so that whoever wants to can work with the photo library from whichever of our other Macs is handy
-
In SCCM 2012 hierarchy client settings
In Sccm 2012 hierarchy how client settings will work in ex:CAS with two primary sites do i have to create client settings from both the primary sites or i can create them from CAS. how this should be.
-
How can i read the data fromtext fieldsin the form of bytes??
Hi friends, How can i read the data fromtext fieldsin the form of byte string while using Socket connection. I have two text fields. i need to send the data from the textfeilds to the server using a byte string. Can anyboday help me??? KK
-
OVI fails to recognize my device
I've installed ovi on my machine and when it asks me to connect the 5800 nothing happens.it says something like 'nokia ovi could not connect,,,,' is there anything i can try?