xmlエディタ---xmleditor
15411 ワード
xmlのエディタについて、ネット上で大量の資料を探して、それから試験を経てやっとxmleditorの機能を完成して、今ソースコードを貼って、みんなが編集することができることを望みます!直接実習して、運行できることを保証します!
実行結果は
import java.io.ByteArrayInputStream;
mport javax.xml.parsers.*;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeSelectionModel;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class XTree extends JTree {
private DefaultMutableTreeNode treeNode;
private DocumentBuilderFactory dbf;
private DocumentBuilder db;
private Document doc;
// public XTree(String text) throws ParserConfigurationException{
// super();
// getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
// setShowsRootHandles(true);
// setEditable(false);
// dbf=DocumentBuilderFactory.newInstance();
// dbf.setValidating(false);
// db=dbf.newDocumentBuilder();
// treeNode=createTreeNode(parseXml(text));
// setModel(new DefaultTreeModel(treeNode));
// }
public XTree(String text)throws ParserConfigurationException{
this();
refresh(text);
// buildTree(text);
}
public void refresh(String text) {
// TODO Auto-generated method stub
setModel(buildTree(text));
}
public XTree()throws ParserConfigurationException{
super();
getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
setShowsRootHandles(true);
setEditable(false);
dbf=DocumentBuilderFactory.newInstance();
dbf.setValidating(false);
db=dbf.newDocumentBuilder();
setModel(buildWelcomTree());
}
private DefaultTreeModel buildTree(String text){
DefaultMutableTreeNode treeNode;
Node newNode;
newNode =parseXml(text);
if(newNode!=null){
treeNode=createTreeNode(newNode);
return new DefaultTreeModel(treeNode);
}
else
return null;
}
private DefaultTreeModel buildWelcomTree(){
DefaultMutableTreeNode root;
DefaultMutableTreeNode instructions,openingDoc,
editingDoc,savingDoc;
DefaultMutableTreeNode openingDocText,editingDocText,
savingDocText;
DefaultMutableTreeNode development,addingFeatures,
contactingKyle;
root=new DefaultMutableTreeNode("Welcome to XML View 1.0");
instructions=new DefaultMutableTreeNode("Welcome to XML View 1.0");
openingDoc=new DefaultMutableTreeNode("Welcome to XML View 1.0");
openingDocText=new DefaultMutableTreeNode("Welcome to XML View 1.0");
editingDoc=new DefaultMutableTreeNode("Welcome to XML View 1.0");
editingDocText=new DefaultMutableTreeNode("Welcome to XML View 1.0");
savingDoc=new DefaultMutableTreeNode("Welcome to XML View 1.0");
savingDocText=new DefaultMutableTreeNode("Welcome to XML View 1.0");
root.add(instructions);
instructions.add(openingDoc);
instructions.add(editingDoc);
openingDoc.add(openingDocText);
editingDoc.add(editingDocText);
return new DefaultTreeModel(root);
}
private DefaultMutableTreeNode createTreeNode(Node root){
DefaultMutableTreeNode treeNode=null;
String type,name,value;
NamedNodeMap attribs;
Node attribNode;
type=getNodeType(root);
name=root.getNodeName();
value=root.getNodeValue();
treeNode=new DefaultMutableTreeNode(root.getNodeType()==Node.TEXT_NODE?value:name);
attribs=root.getAttributes();
if(attribs!=null){
for(int i=0;i<attribs.getLength();i++){
attribNode=attribs.item(i);
name=attribNode.getNodeName().trim();
value=attribNode.getNodeValue().trim();
if(value!=null){
if(value.length()>0){
treeNode.add(new DefaultMutableTreeNode("[Attribute]-->"+name+"=\""+value+"\""));
}
}
}
}
if(root.hasChildNodes()){
NodeList children;
int numChildren;
Node node;
String data;
children=root.getChildNodes();
if(children!=null){
numChildren=children.getLength();
for(int i=0;i<numChildren;i++){
node=children.item(i);
if(node!=null){
if(node.getNodeType()==Node.ELEMENT_NODE){
treeNode.add(createTreeNode(node));
}
data=node.getNodeValue();
if(data!=null){
data=data.trim();
if(!data.equals("
")&&!data.equals("\r
")&&data.length()>0){
treeNode.add(createTreeNode(node));
}
}
}
}
}
}
return treeNode;
}
private String getNodeType(Node node){
String type;
switch(node.getNodeType()){
case Node.ELEMENT_NODE:
{
type="Element";
break;
}
case Node.ATTRIBUTE_NODE:
{
type="Attribute";
break;
}
case Node.TEXT_NODE:
{
type="Text";
break;
}
case Node.CDATA_SECTION_NODE:
{
type="CData section";
break;
}
case Node.ENTITY_NODE:
{
type="Entity";
break;
}
case Node.PROCESSING_INSTRUCTION_NODE:
{
type = "Processing instruction";
break;
}
case Node.COMMENT_NODE:
{
type = "Comment";
break;
}
case Node.DOCUMENT_NODE:
{
type = "Document";
break;
}
case Node.DOCUMENT_TYPE_NODE:
{
type = "Document type";
break;
}
case Node.DOCUMENT_FRAGMENT_NODE:
{
type = "Document fragment";
break;
}
case Node.NOTATION_NODE:
{
type = "Notation";
break;
}
default:
{
type = "???";
break;
}
}
return type;
}
private Node parseXml( String text )
{
ByteArrayInputStream byteStream;
byteStream = new ByteArrayInputStream( text.getBytes() );
try
{
doc = db.parse( byteStream );
}
catch ( Exception e )
{
e.printStackTrace();
System.exit(0);
}
return ( Node )doc.getDocumentElement();
}
}
import javax.swing.*;
import javax.swing.tree.TreeSelectionModel;
import javax.xml.parsers.ParserConfigurationException;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.ArrayList;
public class XmlEditor extends JFrame
{
private XTree xTree;
private JScrollPane jScroll,jScrollRt;
private JTextArea textArea;
private JSplitPane splitPane;
private JButton refreshButton;
private WindowListener winClosing;
private static final int FRAME_WIDTH = 400;
private static final int FRAME_HEIGHT = 300;
public XmlEditor( String title ) throws ParserConfigurationException
{
super( title );
Toolkit toolkit;
Dimension dim, minimumSize;
int screenHeight, screenWidth;
setBackground( Color.lightGray );
getContentPane().setLayout( new BorderLayout() );
toolkit = Toolkit.getDefaultToolkit();
dim = toolkit.getScreenSize();
screenHeight = dim.height;
screenWidth = dim.width;
setBounds( (screenWidth-FRAME_WIDTH)/2, (screenHeight-FRAME_HEIGHT)/2, FRAME_WIDTH, FRAME_HEIGHT );
jScroll = new JScrollPane();
jScrollRt = new JScrollPane();
textArea = new JTextArea( 200,150 );
jScrollRt.getViewport().add( textArea );
xTree = new XTree();
xTree.getSelectionModel().setSelectionMode( TreeSelectionModel.SINGLE_TREE_SELECTION );
xTree.setShowsRootHandles( true );
xTree.setEditable( false );
jScroll.getViewport().add( xTree );
splitPane = new JSplitPane( JSplitPane.HORIZONTAL_SPLIT, jScroll, jScrollRt );
splitPane.setOneTouchExpandable(true);
splitPane.setDividerLocation(200);
minimumSize = new Dimension(200, 150);
jScroll.setMinimumSize( minimumSize );
jScrollRt.setMinimumSize( minimumSize );
splitPane.setPreferredSize( new Dimension(400, 300) );
getContentPane().add( splitPane, BorderLayout.CENTER );
refreshButton = new JButton( "Refresh" );
refreshButton.setBorder(
BorderFactory.createRaisedBevelBorder() );
refreshButton.addActionListener( new RefreshAction());
getContentPane().add( refreshButton, BorderLayout.NORTH );
JMenu fileMenu = new JMenu( "File" );
JMenuItem exitItem = new JMenuItem( "Exit" );
fileMenu.add( exitItem );
JMenuBar menuBar = new JMenuBar();
menuBar.add( fileMenu );
setJMenuBar( menuBar );
exitItem.addActionListener(new exitMenuHandler());
validate();
setVisible(true);
winClosing = new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
exit();
}
};
addWindowListener(winClosing);
}
public XmlEditor( String title, ArrayList xmlText ) throws
ParserConfigurationException
{
this( title );
textArea.setText( ( String )xmlText.get( 0 ) + "
" );
for ( int i = 1; i < xmlText.size(); i++ )
textArea.append( ( String )xmlText.get( i ) + "
" );
xTree.refresh( textArea.getText() );
}
public static void main( String[] args )
{
String fileName = "DocBook.xml";
BufferedReader reader;
String line;
ArrayList xmlText = null;
XmlEditor xmlEditor;
try
{
//if( args.length > 0 )
//{
//fileName = args[0];
if ( fileName.substring( fileName.indexOf( '.' ) ).equals( ".xml" ) )
{
reader = new BufferedReader( new FileReader( fileName ) );
xmlText = new ArrayList();
while ( ( line = reader.readLine() ) != null )
{
xmlText.add( line );
}
reader.close();
xmlEditor = new XmlEditor( "XmlEditor 1.0", xmlText );
}
else
{
help();
}
//}
//else
//{
//xmlEditor = new XmlEditor( "XmlEditor 1.0" );
//}
}
catch( FileNotFoundException fnfEx )
{
System.out.println( fileName + " was not found." );
exit();
}
catch( Exception ex )
{
ex.printStackTrace();
exit();
}
}
private static void help()
{
System.out.println( "
ʹ java XTreeTester yourxmlfilename.xml" );
System.exit(0);
}
// �˳�
private static void exit()
{
System.out.println( "
XTree" );
System.exit(0);
}
class RefreshAction implements ActionListener{
@Override
public void actionPerformed(ActionEvent ae) {
// TODO Auto-generated method stub
if ( ae.getActionCommand().equals( "Refresh" ) )
xTree.refresh( textArea.getText() );
}
}
class newMenuHandler implements ActionListener
{
public void actionPerformed ( ActionEvent ae )
{
// textArea.setText( "" );
// try { // XTree
// xTree = new XTree();
// xTree.getSelectionModel().setSelectionMode( TreeSelectionModel.SINGLE_TREE_SELECTION );
// xTree.setShowsRootHandles( true );
// // , JTree
// xTree.setEditable( false);
// }
// //catch ( Exception ex ){
// //ex.printStackTrace();
//
//
// }
textArea.setText("");
try {
xTree = new XTree();
xTree.getSelectionModel().setSelectionMode( TreeSelectionModel.SINGLE_TREE_SELECTION );
xTree.setShowsRootHandles( true );
// , JTree
xTree.setEditable( false);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
class openMenuHandler implements ActionListener
{
JFileChooser jfc;
Container parent;
int choice;
Component openItem;
openMenuHandler()
{
super();
jfc = new JFileChooser();
jfc.setSize( 400,300 );
jfc.setFileFilter( new XmlFileFilter() );
parent = openItem.getParent();
}
public void actionPerformed( ActionEvent ae )
{
choice = jfc.showOpenDialog( parent );
if ( choice == JFileChooser.APPROVE_OPTION )
{
String fileName, line;
BufferedReader reader;
fileName = jfc.getSelectedFile().getAbsolutePath();
try
{
reader = new BufferedReader(
new FileReader( fileName ) );
textArea.setText( reader.readLine() + "
" );
while ( ( line = reader.readLine() ) != null )
{
textArea.append( line + "
" );
}
reader.close();
xTree.refresh( textArea.getText() );
}catch ( Exception ex )
{
String message = ex.getMessage();
ex.printStackTrace();
}
jfc.setCurrentDirectory( new File( fileName ) );}
}
}
class saveMenuHandler implements ActionListener
{
JFileChooser jfc;
Container parent;
int choice;
Component saveItem;
saveMenuHandler()
{
super();
jfc = new JFileChooser();
jfc.setSize( 400,300 );
jfc.setFileFilter( new XmlFileFilter() );
parent = saveItem.getParent();
}
public void actionPerformed( ActionEvent ae )
{
choice = jfc.showSaveDialog( parent );
if ( choice == JFileChooser.APPROVE_OPTION )
{
String fileName;
File fObj;
FileWriter writer;
fileName = jfc.getSelectedFile().getAbsolutePath();
try {
writer = new FileWriter( fileName );
textArea.write( writer );
writer.close();
}
catch ( IOException ioe )
{
ioe.printStackTrace();
}
jfc.setCurrentDirectory( new File( fileName ) );}
}
}
class exitMenuHandler implements ActionListener
{
public void actionPerformed( ActionEvent ae ) {
exit();
}
}
class XmlFileFilter extends javax.swing.filechooser.FileFilter
{
public boolean accept( File fobj )
{
if ( fobj.isDirectory() )
return true;
else
return fobj.getName().endsWith( ".xml" );
}
public String getDescription()
{
return "*.xml";
}
}
}
実行結果は