解析XML文档(java)

前端之家收集整理的这篇文章主要介绍了解析XML文档(java)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

该程序主要是对XML文档进行解析

package com.corejava.serialClone;

import java.awt.Component;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTree;
import javax.swing.SwingWorker;
import javax.swing.event.TreeModelListener;
import javax.swing.filechooser.FileFilter;
import javax.swing.table.AbstractTableModel;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.CDATASection;
import org.w3c.dom.CharacterData;
import org.w3c.dom.Comment;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;

/**
 * This program displays an XML document as a tree.
 * 
 * @author root 2014-09-29
 */
public class TreeViewer {

	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				JFrame frame = new DOMTreeFrame();
				frame.setTitle("TreeViewer");
				frame.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE);
				frame.setVisible(true);
			}
		});
	}
}

/**
 * This frame contains a tree that displays the contents of an XML document.
 * 
 * @author root
 * 
 */
class DOMTreeFrame extends JFrame {
	private static final int DEFAULT_WIDTH = 400;
	private static final int DEFAULT_HEIGHT = 400;

	private DocumentBuilder builder;

	public DOMTreeFrame() {
		setSize(DEFAULT_WIDTH,DEFAULT_HEIGHT);

		JMenu fileMenu = new JMenu("file");
		JMenuItem openMenu = new JMenuItem("open");
		openMenu.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				openFile();
			}
		});
		fileMenu.add(openMenu);

		JMenuItem exitItem = new JMenuItem("Exit");
		exitItem.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				System.exit(0);
			}
		});
		fileMenu.add(exitItem);

		JMenuBar menuBar = new JMenuBar();
		menuBar.add(fileMenu);
		setJMenuBar(menuBar);
	}

	/*
	 * Open a file and load the document
	 */
	public void openFile() {
		// TODO Auto-generated method stub
		JFileChooser choose = new JFileChooser();
		choose.setCurrentDirectory(new File("dom"));

		choose.setFileFilter(new FileFilter() {

			@Override
			public String getDescription() {
				// TODO Auto-generated method stub
				return "XML files";
			}

			@Override
			public boolean accept(File f) {
				// TODO Auto-generated method stub
				return f.isDirectory()
						|| f.getName().toLowerCase().endsWith(".xml");
			}
		});
		int r = choose.showOpenDialog(this);
		if (r != JFileChooser.APPROVE_OPTION)
			return;
		final File file = choose.getSelectedFile();

		new SwingWorker<Document,Void>() {

			@Override
			protected Document doInBackground() throws Exception {
				// TODO Auto-generated method stub
				if (builder == null) {
					DocumentBuilderFactory factory = DocumentBuilderFactory
							.newInstance();
					builder = factory.newDocumentBuilder();
				}
				return builder.parse(file);
			}

			protected void done() {
				try {

					Document doc = get();
					JTree tree = new JTree(new DOMTreeModel(doc));
					tree.setCellRenderer(new DOMTreeCellRenderer());

					setContentPane(new JScrollPane(tree));
					validate();
				} catch (Exception e) {
					// TODO: handle exception
					JOptionPane.showMessageDialog(DOMTreeFrame.this,e);
				}
			}
		}.execute();
	}
}

/**
 * 
 * @author root
 * 
 */
class DOMTreeModel implements TreeModel {

	private Document doc;

	public DOMTreeModel(Document doc) {
		this.doc = doc;
	}

	@Override
	public Object getRoot() {
		// TODO Auto-generated method stub
		return doc.getDocumentElement();
	}

	@Override
	public Object getChild(Object parent,int index) {
		// TODO Auto-generated method stub
		Node node = (Node) parent;
		NodeList list = node.getChildNodes();
		return list.item(index);
	}

	@Override
	public int getChildCount(Object parent) {
		// TODO Auto-generated method stub
		Node node = (Node) parent;
		NodeList list = node.getChildNodes();
		return list.getLength();
	}

	@Override
	public boolean isLeaf(Object node) {
		// TODO Auto-generated method stub
		return getChildCount(node) == 0;
	}

	@Override
	public void valueForPathChanged(TreePath path,Object newValue) {
		// TODO Auto-generated method stub

	}

	@Override
	public int getIndexOfChild(Object parent,Object child) {
		// TODO Auto-generated method stub
		Node node = (Node) parent;
		NodeList list = node.getChildNodes();
		for (int i = 0; i < list.getLength(); i++)
			if (getChild(node,i) == child)
				return i;
		return -1;
	}

	@Override
	public void addTreeModelListener(TreeModelListener l) {
		// TODO Auto-generated method stub

	}

	@Override
	public void removeTreeModelListener(TreeModelListener l) {
		// TODO Auto-generated method stub

	}
}

/*
 * This class renders as XML node.
 */
class DOMTreeCellRenderer extends DefaultTreeCellRenderer {
	public Component getTreeCellRenderComponent(JTree tree,Object value,boolean selected,boolean expanded,boolean leaf,int row,boolean hasFocus) {
		Node node = (Node) value;
		if (node instanceof Element)
			return elementPanel((Element) node);
		super.getTreeCellRendererComponent(tree,value,selected,expanded,leaf,row,hasFocus);
		if (node instanceof CharacterData)
			setText(characterString((CharacterData) node));
		else
			setText(node.getClass() + ": " + node.toString());
		return this;
	}

	public static JPanel elementPanel(Element e) {
		JPanel panel = new JPanel();
		panel.add(new JLabel("Element: " + e.getTagName()));
		final NamedNodeMap map = e.getAttributes();
		panel.add(new JTable(new AbstractTableModel() {

			@Override
			public Object getValueAt(int rowIndex,int columnIndex) {
				// TODO Auto-generated method stub
				return columnIndex == 0 ? map.item(rowIndex).getNodeName()
						: map.item(columnIndex).getNodeValue();
			}

			@Override
			public int getRowCount() {
				// TODO Auto-generated method stub
				return map.getLength();
			}

			@Override
			public int getColumnCount() {
				// TODO Auto-generated method stub
				return 2;
			}
		}));
		return panel;
	}

	public static String characterString(CharacterData node) {
		StringBuilder builder = new StringBuilder(node.getData());
		for (int i = 0; i < builder.length(); i++) {
			if (builder.charAt(i) == '\r') {
				builder.replace(i,i + 1,"\\r");
				i++;
			} else if (builder.charAt(i) == '\n') {
				builder.replace(i,"\\n");
				i++;
			} else if (builder.charAt(i) == '\t') {
				builder.replace(i,"\\t");
				i++;
			}
		}
		if (node instanceof CDATASection)
			builder.insert(0,"CDATASection:");
		else if (node instanceof Text)
			builder.insert(0,"Text:");
		else if (node instanceof Comment)
			builder.insert(0,"Comment:");

		return builder.toString();
	}
}

实现如图所示


原文链接:https://www.f2er.com/xml/297941.html

猜你在找的XML相关文章