我正在研究JTree,我需要创建Jtree的XML文件,那么有什么好的方法可以转换它吗?我在java中使用JTree。
我只需要转换它,我有Checkbox
作为节点进入树,我已经使用了渲染。当提交调用时,我需要将该Jtree转换为XML。那有什么好办法吗?
我的树是动态创建的。所以我需要转换它。
我试过这个
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
Document doc = factory.newDocumentBuilder().newDocument();
Element rootElement = doc.createElement("Vervesystems");
TreeNode root = (TreeNode) jTree1.getModel().getRoot();
parseTreeNode(root, rootElement);
System.out.println("Node name"+root.toString());
System.err.println("Root node"+root.getChildCount());
Transformer tf = TransformerFactory.newInstance().newTransformer();
tf.setOutputProperty(OutputKeys.INDENT, "yes");
tf.setOutputProperty(OutputKeys.METHOD, "xml");
tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
DOMSource domSource = new DOMSource(doc);
StreamResult sr = new StreamResult(new File("/home/kishan/NetBeansProjects/03-02-2014-VISDashboard/src/com/verve/visdashboard/TreeModel.xml"));
tf.transform(domSource, sr);
} catch (Exception e) {
System.err.println("This is exception "+e);
}
private void parseTreeNode(TreeNode treeNode, Node doc) {
try {
Element parentElement = doc.getOwnerDocument().createElement("folder");
doc.appendChild(parentElement);
System.err.println("Element name"+parentElement.getTagName());
// Apply properties to root element...
org.w3c.dom.Attr attrName = doc.getOwnerDocument().createAttribute("DisplayName");
attrName.setNodeValue("Treenode");
System.err.println("Count"+treeNode.getChildCount());
parentElement.getAttributes().setNamedItem(attrName);
Enumeration kiddies = treeNode.children();
while (kiddies.hasMoreElements()) {
TreeNode child = (TreeNode) kiddies.nextElement();
//doc.appendChild(child);
System.out.println("Child"+child.toString());
parseTreeNode(child, parentElement);
}
} catch (Exception e) {
System.err.println("exception is here"+e);
}
但它的Wrting仅在myxml文件中为空白。任何人都可以提出建议。示例图像在这里。
答案 0 :(得分:4)
基本概念很简单。 TreeModel
只是一堆链接的节点,可能包含也可能不包含子节点
创建XML是一个很小的"实际上,最困难的部分是尝试解析每个节点并保存它...更复杂,但并不困难......
请查看Java API for XML Processing (JAXP)了解详情
import java.io.File;
import java.util.Enumeration;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreeNode;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
public class ConvertToXML {
public static void main(String[] args) {
TreeModel model = new DefaultTreeModel(...);
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
Document doc = factory.newDocumentBuilder().newDocument();
Element rootElement = doc.createElement("treeModel");
doc.appendChild(rootElement);
// Get tree root...
TreeNode root = (TreeNode) model.getRoot();
parseTreeNode(root, rootElement);
// Save the document to disk...
Transformer tf = TransformerFactory.newInstance().newTransformer();
tf.setOutputProperty(OutputKeys.INDENT, "yes");
tf.setOutputProperty(OutputKeys.METHOD, "xml");
tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
DOMSource domSource = new DOMSource(doc);
StreamResult sr = new StreamResult(new File("TreeModel.xml"));
tf.transform(domSource, sr);
} catch (ParserConfigurationException | TransformerException ex) {
ex.printStackTrace();
}
}
private static void parseTreeNode(TreeNode treeNode, Node doc) {
Element parentElement = doc.getOwnerDocument().createElement("node");
doc.appendChild(parentElement);
// Apply properties to root element...
Attr attrName = doc.getOwnerDocument().createAttribute("name");
attrName.setNodeValue(...);
parentElement.getAttributes().setNamedItem(attrName);
Enumeration kiddies = treeNode.children();
while (kiddies.hasMoreElements()) {
TreeNode child = (TreeNode) kiddies.nextElement();
parseTreeNode(child, parentElement);
}
}
}
已更新为可运行示例
以下示例基于How to use Trees
中的示例并产生以下输出......
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Library>
<catagory name="Books for Java Programmers">
<book name="The Java Tutorial: A Short Course on the Basics" url="tutorial.html"/>
<book name="The Java Tutorial Continued: The Rest of the JDK" url="tutorialcont.html"/>
<book name="The JFC Swing Tutorial: A Guide to Constructing GUIs" url="swingtutorial.html"/>
<book name="Effective Java Programming Language Guide" url="bloch.html"/>
<book name="The Java Programming Language" url="arnold.html"/>
<book name="The Java Developers Almanac" url="chan.html"/>
</catagory>
<catagory name="Books for Java Implementers">
<book name="The Java Virtual Machine Specification" url="vm.html"/>
<book name="The Java Language Specification" url="jls.html"/>
</catagory>
</Library>
代码......
import java.io.File;
import java.util.Enumeration;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreeNode;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class TreeExample {
public static void main(String[] args) {
DefaultMutableTreeNode top = new DefaultMutableTreeNode("The Java Series");
createNodes(top);
TreeModel model = new DefaultTreeModel(top);
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
Document doc = factory.newDocumentBuilder().newDocument();
// Get tree root...
DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot();
parseTreeNode(root, doc);
// Save the document to disk...
Transformer tf = TransformerFactory.newInstance().newTransformer();
tf.setOutputProperty(OutputKeys.INDENT, "yes");
tf.setOutputProperty(OutputKeys.METHOD, "xml");
tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
DOMSource domSource = new DOMSource(doc);
StreamResult sr = new StreamResult(new File("TreeModel.xml"));
tf.transform(domSource, sr);
} catch (ParserConfigurationException | TransformerException ex) {
ex.printStackTrace();
}
}
protected static void parseTreeNode(DefaultMutableTreeNode treeNode, Document doc) {
String value = treeNode.getUserObject().toString();
Element rootElement = doc.createElement("Library");
doc.appendChild(rootElement);
Enumeration kiddies = treeNode.children();
while (kiddies.hasMoreElements()) {
DefaultMutableTreeNode child = (DefaultMutableTreeNode) kiddies.nextElement();
parseTreeNode(child, rootElement);
}
}
protected static void parseTreeNode(DefaultMutableTreeNode treeNode, Element doc) {
Object value = treeNode.getUserObject();
Element parentElement = null;
if (value instanceof BookInfo) {
parentElement = doc.getOwnerDocument().createElement("book");
BookInfo book = (BookInfo) value;
// Apply properties to root element...
Attr attrName = doc.getOwnerDocument().createAttribute("name");
attrName.setNodeValue(book.getBookName());
parentElement.getAttributes().setNamedItem(attrName);
Attr attrURL = doc.getOwnerDocument().createAttribute("url");
attrURL.setNodeValue(book.getBookURL());
parentElement.getAttributes().setNamedItem(attrURL);
} else if (value instanceof BookCatagory) {
parentElement = doc.getOwnerDocument().createElement("catagory");
BookCatagory book = (BookCatagory) value;
// Apply properties to root element...
Attr attrName = doc.getOwnerDocument().createAttribute("name");
attrName.setNodeValue(book.getCatagory());
parentElement.getAttributes().setNamedItem(attrName);
}
doc.appendChild(parentElement);
Enumeration kiddies = treeNode.children();
while (kiddies.hasMoreElements()) {
DefaultMutableTreeNode child = (DefaultMutableTreeNode) kiddies.nextElement();
parseTreeNode(child, parentElement);
}
}
protected static void createNodes(DefaultMutableTreeNode top) {
DefaultMutableTreeNode category = null;
DefaultMutableTreeNode book = null;
category = new DefaultMutableTreeNode(new BookCatagory("Books for Java Programmers"));
top.add(category);
//original Tutorial
book = new DefaultMutableTreeNode(new BookInfo("The Java Tutorial: A Short Course on the Basics",
"tutorial.html"));
category.add(book);
//Tutorial Continued
book = new DefaultMutableTreeNode(new BookInfo("The Java Tutorial Continued: The Rest of the JDK",
"tutorialcont.html"));
category.add(book);
//JFC Swing Tutorial
book = new DefaultMutableTreeNode(new BookInfo("The JFC Swing Tutorial: A Guide to Constructing GUIs",
"swingtutorial.html"));
category.add(book);
//Bloch
book = new DefaultMutableTreeNode(new BookInfo("Effective Java Programming Language Guide",
"bloch.html"));
category.add(book);
//Arnold/Gosling
book = new DefaultMutableTreeNode(new BookInfo("The Java Programming Language", "arnold.html"));
category.add(book);
//Chan
book = new DefaultMutableTreeNode(new BookInfo("The Java Developers Almanac",
"chan.html"));
category.add(book);
category = new DefaultMutableTreeNode(new BookCatagory("Books for Java Implementers"));
top.add(category);
//VM
book = new DefaultMutableTreeNode(new BookInfo("The Java Virtual Machine Specification",
"vm.html"));
category.add(book);
//Language Spec
book = new DefaultMutableTreeNode(new BookInfo("The Java Language Specification",
"jls.html"));
category.add(book);
}
public static class BookCatagory {
private String catagory;
public BookCatagory(String cat) {
this.catagory = cat;
}
public String getCatagory() {
return catagory;
}
}
private static class BookInfo {
private String bookName;
private String bookURL;
public BookInfo(String book, String filename) {
bookName = book;
bookURL = filename;
}
public String getBookName() {
return bookName;
}
public String getBookURL() {
return bookURL;
}
public String toString() {
return bookName;
}
}
}
答案 1 :(得分:2)
您应该拥有TreeModel工具Serializable,然后您可以非常简单地将简单Java用于convert to XML和read it back:
XMLEncoder enc = new XMLEncoder(outputStream);
enc.writeObject(treeModelInstance);
并阅读:
XMLDecoder dec = new XMLDecoder(inputStream);
KrishnasTreeModel model = (KrishnasTreeModel)dec.readObject();
OP要求XStream示例,因此:
public class Person {
private String firstname;
private String lastname;
private PhoneNumber phone;
private PhoneNumber fax;
// ... constructors and methods
}
public class PhoneNumber {
private int code;
private String number;
// ... constructors and methods
}
序列化这些:
Person joe = new Person("Joe", "Walnes");
joe.setPhone(new PhoneNumber(123, "1234-456"));
joe.setFax(new PhoneNumber(123, "9999-999"));
XStream xstream = new XStream();
String joeInXml = xstream.toXML(joe);
反序列化很简单:
Person otherJoe = xstream.fromXML(joeInXml);
祝你好运,如果你还有其他问题,请发表评论。请注意,您不一定需要实现Serializable才能使用XStream - 它并不关心。如果您想要customise XStream to generate other XML,也可以使用注释。