White spaces in strings
how do i ignore the white space in a string.
ex:
String str = this is an example;
how do i change it into
String str2 = thisisanexample;
I didn't mean to insult you or anything. I apologize if you took offence. It's just I am an old school C programmer myself and I when ever I work with Strings I have to remind myself that they are immutable objects with a extensive collection of methods not character arrays in which you can manipulate the characters indiviually. Of course there are no String or StringBuffer objects in C. I was simply referring to the process you recommeded of directly manipulating characters in a StringBuffer as being very C like thing to do. You can draw many parallels between working with a StringBuffer and a char array.
Finally I don't have the code anymore. It was some time ago and it was just a test case for a specific problem I had not an exhaustive comparison between StringBuffers and String.replace(). Anyway for what its worth most String methods recast as StringBuffers for char manipulations in their implementations and do so quite efficiently. The average java programmer should avoid this practice themselves unless they have a specific need to do so because 9 out of 10 times they will do so less efficiently than the Java.lang.String implementors.
To avoid this turning into any more of a flame war than it already is, I'll let you have the last word (i.e. I will not be adding anything further to this thread.)
Similar Messages
-
Adding white spaces between strings during concatenation in JSTL
Please provide a way to add white space between strings during concatenation in JSTL.
I tried the following.
eg:
<c:set var="even_odd" value="odd">
<c:out value="first ${even_odd}"/>
I want the output string as "first odd ".
Moreover i am using the above value for generating the class attribute of a row of a table like
<tr class=<c:out value="first ${even_odd}"/>>
while printing the value of <c:out value="first ${even_odd}"/> in the page,i am getting correctly as i needed as "first odd".
But while taking the code of the page while rendering by the browser, it is showing like
<tr class="first" odd="">
I think the white space is the problem.
Please provide any solution or hint.<tr class=<c:out value="first ${even_odd}"/>><tr class="first ${even_odd}">
-
Search for White space within strings
create table emp_dtl
(empname varchar2(23));
Insert into emp_dtl values ('WAYNE');
Insert into emp_dtl values ('JOSEPH KRUPP'); --------- has white space
Insert into emp_dtl values ('YING ZONG LEE'); --------- has white space
Insert into emp_dtl values ('COHEN');
Insert into emp_dtl values ('MARIE');How can i search for empnames which has White space in it? From other OTN threads, I gathered that this has something to do with
chr(32)But i don't know how to put this in LIKE operator.Hi,
SELECT *
FROM emp_dtl
WHERE REGEXP_LIKE (empname, '\s')
;will look for any kind of whitespace (including spaces, which are CHR (32)).
It may be more efficient to specifically list all the different whitespace characters, and see if the string changes when you remove all of them:
SELECT *
FROM emp_dtl
WHERE empname != TRANSLATE ( empname
, 'x ' || CHR (9) -- CHR (9) = <tab>
|| CHR (10) -- CHR (10) = <newline>
|| CHR (13) -- CHR (13) = <return>
, 'x'
;Edited by: Frank Kulash on Jul 12, 2010 8:47 AM -
Remote white space from string
Hi I need a method which will remove the spaces in a string eg "Hello World" -> "HelloWorld"
I have the code below but it dosnt work for the obvious reason charAt() returns a char and im comparing to a string.
Can anyone offer any help? Thanks
public void removeSpace(String s)
{ int rs = s.length();
String cat;
for (int i=0;i<rs;i++) {
cat = s.charAt(i).toString();
if (cat==" ") {
s.replace(""," ");
}Hi I need a method which will remove the spaces in a
string eg "Hello World" -> "HelloWorld"
I have the code below but it dosnt work for the
obvious reason charAt() returns a char and im
comparing to a string.
Can anyone offer any help? Thanks
public void removeSpace(String s)
{ int rs = s.length();
String cat;
for (int i=0;i<rs;i++) {
cat = s.charAt(i).toString();
if (cat==" ") {
s.replace(""," ");
Hi,
You can't modify the contents of a String, you must create a new String, and use that one. Your code should be:
public String removeSpace(String s) {
return s.replaceAll(" ", "");
}The returned string is the string without spaces.
/Kaj -
i all,
I'm trying to use Scan From String in order to parse some data coming in from UDP.
Input String: ASCII [00 01 02 03 ... FF]
What I want: s[00 .. 30] d[12], d[34], d[56] leftover s[37 38 39 ... FF]
ATTEMPT1
Format String: %49s%2d%2d%2d
What I get: s[00-09] RUNTIME ERROR!
ATTEMPT2
Format String: %49[^]%2d%2d%2d
What I get: Only allows first output. Will error out if I use any additional outputs from Scan From String
ATTEMPT3
Format String: %49[^(0xFF)]%2d%2d%2d Value in () is ASCII character FF.
What I get: s[00 .. 30] d[12], d[34], d[56] leftover s[37 38 39 ... FF]
It appears as though when I use %##[^] it thinks I'm looking for the ENTIRE string so it will not let me add any more Formatting. If I add a delimiter other than ^ it will run, and it will work presuming that character isn't within the first 49 characters... and I can't guarentee that it won't.
I'm aware I can parse my string using subsets and whatnot... but Scan From String is so elegant. It would be great if %S allowed for white space... or if $##[^] would simply take the first ## characters and allow me to Format after that.
Is there a simple, elegant way to do this? I wish my dataset was only 3-4 outputs. It'd be ideal if I could. Thanks.
Edit:
It might be more helpful if I provide a less abstract example:
I have an ASCII Header (Finite Length String), a Sender IP (Finite Length String), a Timestamp, a Message ID (Finite Length Decimal), A Message in ASCII ( '1' actually means 0x31, not 0x01) And for some ungodly reason... no delimiters.
So I was HOPING %##s%##s%<%H:%M:%s>t%##d (With leftover string to be my message) would work, but if any white space is contained within there... it messes up.I cannot provide exact strings because the string is actually ASCII characters, most of which aren't displayable.
I have a string where I have:
24 ASCII Characters representing 6x U32 Header Data
13 ASCII characters represening the sender IP (string)
12 ASCII Characters representing the name of the message (String)
12 ASCII Characters representing 3x U32 Data
12 ASCII Characters represneting the name of packet (String)
12 ASCII Characters representing 12x U8 Data
256 ASCII Characters represening 256x U8 Data
etc...
It would be ideal to simply Scan from the string and output the data with the appropriate data types already assigned instead of splitting string and type casting each individualy. But if, for example, my header starts with an ASCII representation of a U32 of 2560(decimal) it would look like this: [00][00][0A][00]. ASCII 0A is considered white space. So my header would only contain 2 ASCII characters instead of the desired 24. -
How do I remove extra white spaces in a string?
How do I remove extra white spaces in a string?
trim() removes before and after spaces.
If I have a string "This is Test"
I want to remove extra spaces between words and also I want to keep SINGLE space
between words. So output should be "This is Test". Thanks.replaceAll dosen't support with my version. Actually this works..............!!!!!!!!! Thank you.
java.util.StringTokenizer st = new java.util.StringTokenizer(brn, " \t");
StringBuffer buf = new StringBuffer();
while (st.hasMoreTokens()) {
buf.append(" ").append(st.nextToken());
String brn1 = buf.toString().trim(); -
Delete white spaces between two strings
hi!
How do I remove white spaces between two strings. I have attached file for reference.
Thanks
Attachments:
untitled4.JPG 62 KBYou first need to define what you consider to be "whitespace". Is it just a space? Is it spaces and linefeeds? What about carriage returns? Tabs? Anything non-alphabetic and/or non-numeric?
As mentioned previously, the Search and Replace String can be used to delete characters by wiring an empty string to the replace string input. The following, for example, will delete all spaces:
If you need to delete other whitespace characters, just call it again on the resulting string.
Message Edited by smercurio_fc on 06-02-2008 09:25 AM
Attachments:
Example_VI1.png 3 KB -
Hi Guys
I am a Java guy and was really surprised to find something which i cudnt believe . plz help me.
How can i find whether a String is a white space in Oracle. I am having a check for the same in my Procedure.
for e.g.
select length(trim(' ')) from dual
This query returns what?... I cudnt understand its output.I thought it would be returning output as 0.An empty string is null in Oracle, so the length of null is nalso null.
SQL> select 'whitespace' from dual
2 where trim(' ') is null;
'WHITESPAC
whitespace
SQL> edi
Wrote file afiedt.sql
1 select 'whitespace' from dual
2* where trim('1 ') is null
SQL> /
no rows selected
SQL> select nvl(length(trim(' ')),0) from dual;
NVL(LENGTH(TRIM('')),0)
0 -
White spaces append to restulting strings
Hello All,
I'm faced with a weird issue. There are white spaces append to the strings. The only workaround I have is to use the TRIM function. However, I sense that this this maybe be a characterset conversion issue.
I've included the NLS setting for bother Oracle and MySQL as well as my odbc.ini file
QUERY:
SQL> select '"'|| "User" ||'"' as Username from "user"@MYODBC5;
Results (there is white spaces added right after the username, as the result shoudl have been "intm","root" as opposed to "intm "
===============================================================================================================
USERNAME
"intm
USERNAME
"root
QUERYWORK AROUND:
SQL> select '"'|| trim("User") ||'"' as Username from "user"@MYODBC5;
USERNAME
"root"
"intm"
NLS _SETTINGS ORACLE
==============================================================
Oracle:
======
NAME
VALUE$
NLS_LANGUAGE
AMERICAN
NLS_TERRITORY
AMERICA
NLS_CURRENCY
$
NLS_ISO_CURRENCY
AMERICA
NLS_NUMERIC_CHARACTERS
NLS_CHARACTERSET
AL32UTF8
NLS_CALENDAR
GREGORIAN
NLS_DATE_FORMAT
DD-MON-RR
NLS_DATE_LANGUAGE
AMERICAN
NLS_SORT
BINARY
NLS_TIME_FORMAT
HH.MI.SSXFF AM
NAME
VALUE$
NLS_TIMESTAMP_FORMAT
DD-MON-RR HH.MI.SSXF
F AM
NLS_TIME_TZ_FORMAT
HH.MI.SSXFF AM TZR
NLS_TIMESTAMP_TZ_FORMAT
DD-MON-RR HH.MI.SSXF
F AM TZR
NLS_DUAL_CURRENCY
$
NLS_COMP
BINARY
NLS_LENGTH_SEMANTICS
BYTE
NLS_NCHAR_CONV_EXCP
FALSE
NAME
VALUE$
NLS_NCHAR_CHARACTERSET
AL16UTF16
NLS_RDBMS_VERSION
11.2.0.2.0
NLS _SETTINGS MYSQL
==============================================================
Oracle:
======
NAME :
+--------------------------+----------------------------+
| Variable_name | Value |
+--------------------------+----------------------------+
| character_set_client | utf8 |
| character_set_connection | utf8 |
| character_set_database | latin1 |
| character_set_filesystem | binary |
| character_set_results | utf8 |
| character_set_server | latin1 |
| character_set_system | utf8 |
| character_sets_dir | /usr/share/mysql/charsets/ |
+--------------------------+----------------------------+
===========================================================ODBC INI
[myodbc5]
Driver = /usr/lib64/libmyodbc5a.so
Description = Connector/ODBC 5.3.4 Driver DSN
SERVER = 127.0.0.1
PORT = 3306
USER = intm
PASSWORD = *********
DATABASE = mysql
OPTION = 0
TRACE = OFFHi,
I reproduced the problem on my systems with Oracle AL32UTF8 and MySQL latin1 database selecting from a char column.
The solution was to add -
CHARSET=latin1
to the MySQL odbc.ini entry.
If I set -
CHARSET=utf8
then the problem happened.
Try this and let us know what happens.
Regards,
Mike -
White space handling dbms_xmlstore.insertxml
Hi,
I have a question about white space handling.
I have a column in table which holds white space character.
When I loading xml file using dbms_xmlstore.insertxml white space is converted into NULL and inserted into table.
It would fail if the column type is not null.
How do I handle it?
======================================================
Alternatively, how do I insert a tag with only whitespace in it into a table?
<Tag> </Tag> [One whitespace]
To elaborate the question
If I have following data in xml file ...
=============================================
<Rowset>
<Row>
<Tag1> </Tag1>
<Tag2>1</Tag1>
</Row>
</Rowset>
I have to load this data into
table tab1...
create table tab1 (tag1 varchar2(5), tag2 number);
How do I achieve it using dbms_xmlstore so that I can read the whitespace in XML and load it correctly into the table?
========================================================================
To use an alternate approach, I also tried the following.....
I tried the following test program on the xml file also shown below....
XML File is
<?xml version="1.0"?>
<ROWSET>
<ROW>
<SYS_NAME> a </SYS_NAME>
<SYS_SERIAL_NUM>000000</SYS_SERIAL_NUM>
</ROW>
</ROWSET>
And small procedure is
create or replace procedure PRO_TEST
as
o_sys_name varchar(10);
spacetag varchar2(10) := ' ';
begin
--execute immediate 'create global temporary table gt_xmltype_tab1 (xmlfile1 xmltype)';
insert into gt_xmltype_tab(xmlfile1)
values(XMLType(bfilename('RESTOREDIR','ADTL_SETUP_OPTIONS.xml'),nls_charset_id('AL32UTF8')));
select extractvalue (value(x), '/ROW/SYS_NAME')
into o_sys_name
from gt_xmltype_tab gt, TABLE(XMLSequence(extract(gt.xmlfile1, '/ROWSET/ROW'))) x;
dbms_output.put_line('[' || o_sys_name || ']');
dbms_output.put_line('ASCII:- ' || ascii(o_sys_name));
if o_sys_name = ' ' then
--if o_sys_name = chr(32) then
dbms_output.put_line('I found space');
else
dbms_output.put_line('I found no space');
end if;
commit;
end;
When Tag is <sys_nam> </sys_name> I get [] in the output(empty).
When Tag is <sys_nam> a</sys_name> I get [ a] in the output(space and a).
When Tag is <sys_nam> a </sys_name> I get [ a ] in the output(space a space).
When I has some character along with the whitespace, behaviour is correct and as expected.
But when the tag contains only whitespace the output is empty.
I cant seem to get around this problem.
Upon receiving empty string, other sub systems which are reading the data stop working.
Can someone help here?
Edited by: userAtoZ on May 14, 2011 2:57 PMWhite space handling dbms_xmlstore.insertxmlYou may replace all whitespaces with its corresponding html entity:
SQL> create table test (v varchar2 (5))
Table created.
SQL> declare
ctx sys.dbms_xmlstore.ctxtype := dbms_xmlstore.newcontext ('test');
doc xmltype := xmltype(replace('<ROW><V> </V></ROW>',' ', '&#32;'));
ret int;
begin
ret := dbms_xmlstore.insertxml (ctx, doc);
dbms_xmlstore.closecontext (ctx);
end;
PL/SQL procedure successfully completed.
SQL> select v, length (v), ascii(v) from test
V LENGTH(V) ASCII(V)
1 32
1 row selected. -
A form field to insert white space
Hi all,
I need to insert some white space (the number of these white space is depending to some condition) in a form field.
I show in my report a value and then I must complete this value with some white space to have finally a string with a fixed number of characters.
I have a form field with a value (<?VALUE?>) and then I would insert a new form field to show only some white space. I can not add these white space directly on the field form containing the value.
ThanksBalaji wrote:
I need insert white space into table which a VARCHAR2 column. Just insert it, Whats the issue?
I would like to validate the below expression against the data in the column \S.* What is this expression and where did you get it from?
I guess this pattern validates for non-whitespace characters. Anyone help me on this and explain what this pattern does?No in regular expression space is represented as [:space:]
Please read {message:id=9360002} -
How to set white spaces between the fields in dataset??
Hi all,
I am writing a set on information to from infotypes to a text file. Its a fixed width file. How do set white spaces in the fields for dataset?
Example:
TYPES: begin of header,
filler(40) type c,
id(3) type c,
filler2(7) type c,
delimiter type c,
end of header.
DATA header type header.
header-filler1 = ' '.
header-id = '100'.
header-filler2 = ' '.
header-delimiter = cl_abap_char_utilities=>newline. ( do it to get a new line)
my_table = header.
append my_table.
DATA: out_file(256) type C,
codepage_ref type ref to CX_SY_CONVERSION_CODEPAGE,
out_char type c,
size type i,
insert_string type string,
insert_size type i.
out_file = filename.
open dataset out_file for output in text mode ENCODING NON-UNICODE.
LOOP AT my_table.
size = strlen( my_table ).
insert_string = ''.
DO size TIMES.
offset = sy-index - 1.
try.
out_char = my_table+offset(1).
IF out_char = SPACE.
CONCATENATE insert_string '' INTO insert_string SEPARATED BY SPACE.
ELSE.
CONCATENATE insert_string out_char INTO insert_string.
transfer insert_string to out_file NO END OF LINE .
insert_string = ''.
ENDIF.
catch CX_SY_CONVERSION_CODEPAGE.
insert_size = strlen( insert_string ) - 1.
insert_string = insert_string(insert_size).
endtry.
ENDDO.
transfer CL_ABAP_CHAR_UTILITIES=>NEWLINE TO out_file NO END OF LINE.
ENDLOOP.
close dataset out_file.
How do I get to insert the space for filler1 and filler2?
Edited by: Siong Chao on Oct 4, 2011 4:56 AM
Edited by: Siong Chao on Oct 4, 2011 8:27 AM
Edited by: Siong Chao on Oct 4, 2011 8:29 AMproblem lies in the open dataset codes
Used:
open dataset out_file for output in text mode encoding non-unicode message msg.
if sy-subrc= 0.
loop at my_table.
transfer my_table to out_file
transfer cl_abap_char_utilities=>newline to out_file no end of line.
endloop. -
Problem in parsing white spaces using if_ixml_parser
Hello People,
I have a problem in parsing XML file in one of my programs.
The program uses the method get_value( ) of class if_ixml_node to fetch a value. In the XML file when the value is spaceA, then after parsing, the value fetched is A and not spaceA.
Is there any way to fetch the white spaces also?
Here is the sample tag. The value inside the tags is " A" and after parsing I get "A" the blank is ignored.
<ns1:IndiceCible> A</ns1:IndiceCible>
DATA : l_node_fils TYPE REF TO if_ixml_node.
indice_val = l_node_fils->get_value( ).
In some XML parsing forums I saw that if we add the option as shown below, then the parsing works properly. But this did not work in my case.
<ns1:IndiceCible xml:space="preserve"> A</ns1:IndiceCible>
The input XML file is as follows.
<?xml version="1.0" encoding="UTF-8"?><SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"><SOAP-ENV:Header><env:Flow xmlns:env="http://xml.inetpsa.com/Structure/Informatique/DeveloppementSI/ReferentielEchange"><env:MessageID>0414
2636F4888F4B4A579A21E10000000A52931C</env:MessageID><env:From>R3P INTERFACES</env:From><env:To>SAP</env:To><env:TimeStamp>2010-03-04T14:26:36.672+01:00</env:TimeStamp></env:Flow></SOAP-ENV:Header><SOAP-ENV:Body><env:Response xmlns:env="http://xml.inetpsa.
com/Structure/Informatique/DeveloppementSI/ReferentielEchange"><env:Values><ns1:ListeTranscodifications xmlns:ns1="http://xml.inetpsa.com/ProduitProcess/Produit/Transcodification"><ns1:Transcodification id="1 "><ns1:Statut>KO</ns1:Statut><ns1:Message>ERRO
R : Indice incorrect</ns1:Message><ns1:ReferenceCible>969099979A</ns1:ReferenceCible><ns1:IndiceCible> A</ns1:IndiceCible><ns1:ColoreCible>SS_TEINTE</ns1:ColoreCible></ns1:Transcodification></ns1:ListeTranscodifications></env:Values><env:Status><env:Code>
0</env:Code><env:Label></env:Label></env:Status></env:Response></SOAP-ENV:Body></SOAP-ENV:Envelope>
Regards,
Praveenuse IF_XML_PARSER~CL_ADD_PRESERVE_SPACE_ELEMENT method:
PARAMETERS preserve TYPE flag AS checkbox.
DATA lo_ixml TYPE REF TO if_ixml.
DATA lo_streamfactory TYPE REF TO if_ixml_stream_factory.
DATA lo_parser TYPE REF TO if_ixml_parser.
DATA lo_istream TYPE REF TO if_ixml_istream.
DATA lo_document TYPE REF TO if_ixml_document.
DATA lo_node TYPE REF TO if_ixml_node.
DATA l_node_value TYPE string.
lo_ixml = cl_ixml=>create( ).
lo_streamfactory = lo_ixml->create_stream_factory( ).
lo_istream = lo_streamfactory->create_istream_string(
string = '<?xml version="1.0" encoding="iso-8859-1"?><DATA> WAAA</DATA>' ).
lo_document = lo_ixml->create_document( ).
lo_parser = lo_ixml->create_parser( stream_factory = lo_streamfactory
istream = lo_istream
document = lo_document ).
IF preserve = 'X'.
lo_parser->ADD_PRESERVE_SPACE_ELEMENT( ). "<========= HERE
ENDIF.
lo_parser->parse( ).
lo_node = lo_document->find_from_name( name = 'DATA').
l_node_value = lo_node->get_value( ).
ASSERT ( preserve = 'X' AND l_node_value = ' WAAA' )
OR ( preserve = space AND l_node_value = 'WAAA' ). -
White spaces in token area of xsd - error when importing xsd as ext. def.
Hello,
we are not sure about this issue.
This is how an area of the xsd (unfortunately an xsd of a published standard message format of german government!)
is defined that we need to import as an external definition:
<xs:complexContent>
<xs:restriction base="tns:WLT_String">
<xs:sequence>
<xs:element name="content">
<xs:simpleType>
<xs:restriction base="xs:token">
<xs:enumeration value="Allgemeine Fahrerlaubnis (§ 5 StVZO) " />
<xs:enumeration value="Dienstfahrerlaubnis-Klassen (bisheriger § 5 i. V. m. § 14 StVZO)" />
<xs:enumeration value="Dienstfahrerlaubnis-Klassen (§ 6 i. V. m. § 26 FeV)" />
<xs:enumeration value="Dienstfahrerlaubnis-Klassen Bundeswehr (bisheriger § 5 i. V. m. § 14 StVZO)" />
</xs:restriction>
</xs:simpleType>
</xs:element>
</xs:sequence>
<xs:attribute name="wl_fassung" type="xs:string" use="optional" default="0" />
<xs:attribute name="wl_version" type="xs:string" use="required" fixed="1.1" />
</xs:restriction>
</xs:complexContent>
So we can see this defintion:
<xs:restriction base="xs:token">
which means per definition:
xsd:token: normalizedString w/o 2 white spaces succeeding and w/o white spaces at start and end.
But you can see that the enumerations contain 2 white spaces succeeding or white space at the end.
Impporting this xsd as an external definition into PI will fail.
So it looks like PI is doing a very restricitve check of the values against the token definition.
We would expect that any xml editor would do the same check but behaviour of xml editors is different means accepting this xsd.
So is it correct that PI is more restrictive at the latest during activation of such an xsd?
This results in the situation that official standard xsds will be used by governement with other tools but only interfaces with PI will fail..
Any ideas how to run with that issue?
Regards
DirkHello,
Your issue looks like the one described in this page:
http://www.xmlplease.com/normalized
For reference purposes, here is the link for the supported schema and wsdl in PI 7.1
http://www.sdn.sap.com/irj/sdn/go/portal/prtroot/docs/library/uuid/00a9a425-1769-2a10-9196-bd8eeed72e4c
As a temporary work around, you can try editing the xsd by removing the spaces before importing it into PI.
Hope this helps,
Mark -
Remove white space nodes from jtree
I am trying to create jtree using XML DOM.
But I m not able to remove/ignore the white space elements from DOM.
I am getting output something like this
for example
Server
Text
node1
Text
I want something like this.
Server
node1
I tried all option for removeing the white space
Here I am posting the source
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import java.io.File;
import java.io.IOException;
import org.w3c.dom.Document;
import org.w3c.dom.DOMException;
// Basic GUI components
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
// GUI components for right-hand side
import javax.swing.JSplitPane;
import javax.swing.JEditorPane;
// GUI support classes
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.WindowEvent;
import java.awt.event.WindowAdapter;
// For creating borders
import javax.swing.border.EmptyBorder;
import javax.swing.border.BevelBorder;
import javax.swing.border.CompoundBorder;
// For creating a TreeModel
import javax.swing.tree.*;
import javax.swing.event.*;
import java.util.*;
public class DomEcho02 extends JPanel
// Global value so it can be ref'd by the tree-adapter
static Document document;
static final int windowHeight = 460;
static final int leftWidth = 300;
static final int rightWidth = 340;
static final int windowWidth = leftWidth + rightWidth;
public DomEcho02()
// Make a nice border
EmptyBorder eb = new EmptyBorder(5,5,5,5);
BevelBorder bb = new BevelBorder(BevelBorder.LOWERED);
CompoundBorder cb = new CompoundBorder(eb,bb);
this.setBorder(new CompoundBorder(cb,eb));
// Set up the tree
JTree tree = new JTree(new DomToTreeModelAdapter());
// Iterate over the tree and make nodes visible
// (Otherwise, the tree shows up fully collapsed)
//TreePath nodePath = ???;
// tree.expandPath(nodePath);
// Build left-side view
JScrollPane treeView = new JScrollPane(tree);
treeView.setPreferredSize(
new Dimension( leftWidth, windowHeight ));
// Build right-side view
JEditorPane htmlPane = new JEditorPane("text/html","");
htmlPane.setEditable(false);
JScrollPane htmlView = new JScrollPane(htmlPane);
htmlView.setPreferredSize(
new Dimension( rightWidth, windowHeight ));
// Build split-pane view
JSplitPane splitPane =
new JSplitPane( JSplitPane.HORIZONTAL_SPLIT,
treeView,
htmlView );
splitPane.setContinuousLayout( true );
splitPane.setDividerLocation( leftWidth );
splitPane.setPreferredSize(
new Dimension( windowWidth + 10, windowHeight+10 ));
// Add GUI components
this.setLayout(new BorderLayout());
this.add("Center", splitPane );
} // constructor
public static void main(String argv[])
if (argv.length != 1) {
System.err.println("Usage: java DomEcho filename");
System.exit(1);
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
//factory.setValidating(true);
//factory.setNamespaceAware(true);
try {
DocumentBuilder builder = factory.newDocumentBuilder();
document = builder.parse( new File(argv[0]) );
makeFrame();
} catch (SAXException sxe) {
// Error generated during parsing)
Exception x = sxe;
if (sxe.getException() != null)
x = sxe.getException();
x.printStackTrace();
} catch (ParserConfigurationException pce) {
// Parser with specified options can't be built
pce.printStackTrace();
} catch (IOException ioe) {
// I/O error
ioe.printStackTrace();
} // main
public static void makeFrame() {
// Set up a GUI framework
JFrame frame = new JFrame("DOM Echo");
frame.addWindowListener(
new WindowAdapter() {
public void windowClosing(WindowEvent e) {System.exit(0);}
// Set up the tree, the views, and display it all
final DomEcho02 echoPanel =
new DomEcho02();
frame.getContentPane().add("Center", echoPanel );
frame.pack();
Dimension screenSize =
Toolkit.getDefaultToolkit().getScreenSize();
int w = windowWidth + 10;
int h = windowHeight + 10;
frame.setLocation(screenSize.width/3 - w/2,
screenSize.height/2 - h/2);
frame.setSize(w, h);
frame.setVisible(true);
} // makeFrame
// An array of names for DOM node-types
// (Array indexes = nodeType() values.)
static final String[] typeName = {
"none",
"Element",
"Attr",
"Text",
"CDATA",
"EntityRef",
"Entity",
"ProcInstr",
"Comment",
"Document",
"DocType",
"DocFragment",
"Notation",
// This class wraps a DOM node and returns the text we want to
// display in the tree. It also returns children, index values,
// and child counts.
public class AdapterNode
org.w3c.dom.Node domNode;
// Construct an Adapter node from a DOM node
public AdapterNode(org.w3c.dom.Node node) {
domNode = node;
// Return a string that identifies this node in the tree
// *** Refer to table at top of org.w3c.dom.Node ***
public String toString() {
String s = typeName[domNode.getNodeType()];
String nodeName = domNode.getNodeName();
if (! nodeName.startsWith("#")) {
s += ": " + nodeName;
if (domNode.getNodeValue() != null) {
if (s.startsWith("ProcInstr"))
s += ", ";
else
s += ": ";
// Trim the value to get rid of NL's at the front
String t = domNode.getNodeValue().trim();
int x = t.indexOf("\n");
if (x >= 0) t = t.substring(0, x);
s += t;
return s;
* Return children, index, and count values
public int index(AdapterNode child) {
//System.err.println("Looking for index of " + child);
int count = childCount();
for (int i=0; i<count; i++) {
AdapterNode n = this.child(i);
if (child.domNode == n.domNode) return i;
return -1; // Should never get here.
public AdapterNode child(int searchIndex) {
//Note: JTree index is zero-based.
org.w3c.dom.Node node =
domNode.getChildNodes().item(searchIndex);
return new AdapterNode(node);
public int childCount() {
return domNode.getChildNodes().getLength();
// This adapter converts the current Document (a DOM) into
// a JTree model.
public class DomToTreeModelAdapter
implements javax.swing.tree.TreeModel
// Basic TreeModel operations
public Object getRoot() {
//System.err.println("Returning root: " +document);
return new AdapterNode(document);
public boolean isLeaf(Object aNode) {
// Determines whether the icon shows up to the left.
// Return true for any node with no children
AdapterNode node = (AdapterNode) aNode;
if (node.childCount() > 0) return false;
return true;
public int getChildCount(Object parent) {
AdapterNode node = (AdapterNode) parent;
return node.childCount();
public Object getChild(Object parent, int index) {
AdapterNode node = (AdapterNode) parent;
return node.child(index);
public int getIndexOfChild(Object parent, Object child) {
AdapterNode node = (AdapterNode) parent;
return node.index((AdapterNode) child);
public void valueForPathChanged(TreePath path, Object newValue) {
// Null. We won't be making changes in the GUI
// If we did, we would ensure the new value was really new,
// adjust the model, and then fire a TreeNodesChanged event.
* Use these methods to add and remove event listeners.
* (Needed to satisfy TreeModel interface, but not used.)
private Vector listenerList = new Vector();
public void addTreeModelListener(TreeModelListener listener) {
if ( listener != null
&& ! listenerList.contains( listener ) ) {
listenerList.addElement( listener );
public void removeTreeModelListener(TreeModelListener listener) {
if ( listener != null ) {
listenerList.removeElement( listener );
// Note: Since XML works with 1.1, this example uses Vector.
// If coding for 1.2 or later, though, I'd use this instead:
// private List listenerList = new LinkedList();
// The operations on the List are then add(), remove() and
// iteration, via:
// Iterator it = listenerList.iterator();
// while ( it.hasNext() ) {
// TreeModelListener listener = (TreeModelListener) it.next();
* Invoke these methods to inform listeners of changes.
* (Not needed for this example.)
* Methods taken from TreeModelSupport class described at
* http://java.sun.com/products/jfc/tsc/articles/jtree/index.html
* That architecture (produced by Tom Santos and Steve Wilson)
* is more elegant. I just hacked 'em in here so they are
* immediately at hand.
public void fireTreeNodesChanged( TreeModelEvent e ) {
Enumeration listeners = listenerList.elements();
while ( listeners.hasMoreElements() ) {
TreeModelListener listener =
(TreeModelListener) listeners.nextElement();
listener.treeNodesChanged( e );
public void fireTreeNodesInserted( TreeModelEvent e ) {
Enumeration listeners = listenerList.elements();
while ( listeners.hasMoreElements() ) {
TreeModelListener listener =
(TreeModelListener) listeners.nextElement();
listener.treeNodesInserted( e );
public void fireTreeNodesRemoved( TreeModelEvent e ) {
Enumeration listeners = listenerList.elements();
while ( listeners.hasMoreElements() ) {
TreeModelListener listener =
(TreeModelListener) listeners.nextElement();
listener.treeNodesRemoved( e );
public void fireTreeStructureChanged( TreeModelEvent e ) {
Enumeration listeners = listenerList.elements();
while ( listeners.hasMoreElements() ) {
TreeModelListener listener =
(TreeModelListener) listeners.nextElement();
listener.treeStructureChanged( e );
}DocumentBuilderFactory can be configured to ignore white space.
http://java.sun.com/j2se/1.5.0/docs/api/javax/xml/parsers/DocumentBuilderFactory.html#setIgnoringElementContentWhitespace(boolean)
Maybe you are looking for
-
Photomerge not working on photoshop CC
Hello Photomerge not exist on my Photoshop CC (french) (14,2,1 x64 mac) Files don't exist error 48 Ligne: 46 -> $.evalFile(g_StackScriptFolderPath + "StackSupport.jsx"); How can I get it ?
-
Quotation output through e-mail
Hi All, I am working on quotation, i need to send quotation output through e-mail to distributors, i am not finding output type(Method) e-mail in output types in IMG , please help in how to configure this.send me any document related to this to the
-
Hi All, I have requirement that I need to start an RMI Server before I connect and use the components registered in it. So I have used the ProcessBuilder to start the external process. The process seems to be starting fine but all the logging is not
-
MetaData API, dynamic value provider
Hello, Regarding MetaData API service- Dynamic Value Provider implementation, The values assigned to the properties can either be specified in a free text field or as a fixed list of pre-configured values. Is it possible to have some properties with
-
Win 10 home fail to install several times. What next?
Windows 10 home update is listed as failed several times. Why, What's wrong, and can I fix it?