pbootcms网站模板|日韩1区2区|织梦模板||网站源码|日韩1区2区|jquery建站特效-html5模板网

如何使 xml 模式與 JTable、xml java 相關(鏈接)?

How to make xml schema relate(link) to JTable,xml java?(如何使 xml 模式與 JTable、xml java 相關(鏈接)?)
本文介紹了如何使 xml 模式與 JTable、xml java 相關(鏈接)?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!

問題描述

在這里你可以看到我的申請:

那么我需要做什么:

我不知道如何通過代碼鏈接 xml 架構與所有類型(int、string、float)的 JTable.比如說 Year 是 int 類型,而 schema 是 int ,我如何鏈接它?我不知道英文鏈接或關聯如何.在這個應用程序中,我將所有數據寫入 xml 文件,當應用程序加載時,它會從 xml 文件加載所有數據.

我在這里創建 xml 架構:

 public void CreateSchema(String FileName){文件=文件名;JAXB上下文 jc;嘗試 {jc = JAXBContext.newInstance(XmlSchemaType.class);jc.generateSchema(new SchemaOutputResolver() {@覆蓋公共 javax.xml.transform.Result createOutput(字符串 namespaceURI,字符串建議文件名)拋出 IOException {建議文件名=文件+.xsd";返回新的 StreamResult(suggestedFileName);}});} 捕捉(IOException e){e.printStackTrace();} 捕捉(JAXBException e){e.printStackTrace();}}

這里是所有類型:

 import javax.xml.bind.annotation.XmlAccessType;導入 javax.xml.bind.annotation.XmlAccessorType;導入 javax.xml.bind.annotation.XmlAttribute;導入 javax.xml.bind.annotation.XmlElement;導入 javax.xml.bind.annotation.XmlRootElement;@XmlAccessorType(XmlAccessType.FIELD)@XmlRootElement(name = "自動")公共類 XmlSchemaType {行[] 行;}類行{@XmlAttribute字節ID;@XmlElement字符串 VIN;@XmlElement字符串制作;@XmlElement字符串模型;@XmlElement整數年;@XmlElement字符串描述;@XmlElement浮動成本;}

這里正在寫入 xml 文件:

public void CreateXml(JTable tb,JTable tb2,String FileName){嘗試 {文件=文件名;DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();DocumentBuilder docBuilder = docFactory.newDocumentBuilder();文檔 doc = docBuilder.newDocument();元素 rootElement = doc.createElement("Auto");doc.appendChild(rootElement);int i=0,j=0,k=0;而 (i

在這里加載我的 xml 文件:

 public void PopulateDataSet(JTable tb,JTable tb2,String FileName){文件=文件名;文件 f= 新文件(文件+.xml");如果(f.exists()){嘗試 {DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();文檔 doc = dBuilder.parse(f);doc.getDocumentElement().normalize();NodeList nList = doc.getElementsByTagName("Row");for (int temp = 0; temp < nList.getLength(); temp++) {節點 nNode = nList.item(temp);if (nNode.getNodeType() == Node.ELEMENT_NODE) {元素 eElement = (元素) nNode;DefaultTableModel 模型 = (DefaultTableModel) tb.getModel();model.addRow(new Object[] { "", "","","","Delete" });tb.getModel().setValueAt(eElement.getElementsByTagName("VIN").item(0).getTextContent(),temp, 0);tb.getModel().setValueAt(eElement.getElementsByTagName("Make").item(0).getTextContent(),temp, 1);tb.getModel().setValueAt(eElement.getElementsByTagName("Make").item(0).getTextContent(),temp, 2);tb.getModel().setValueAt(eElement.getElementsByTagName("Year").item(0).getTextContent(),temp, 3);tb.getModel().setValueAt("刪除",temp, 4);DefaultTableModel model2 = (DefaultTableModel) tb2.getModel();model2.addRow(new Object[] { (tb2.getRowCount()+1), "","","","刪除" });tb2.getModel().setValueAt(eElement.getElementsByTagName("VIN").item(0).getTextContent(),temp, 1);tb2.getModel().setValueAt(eElement.getElementsByTagName("Description").item(0).getTextContent(),temp, 2);tb2.getModel().setValueAt(eElement.getElementsByTagName("Cost").item(0).getTextContent(),temp, 3);tb2.getModel().setValueAt("刪除",temp, 4);}}} 捕捉(異常 e){e.printStackTrace();}}如果(!f.exists()){CreateXml(tb,tb2,文件);創建模式(文件);}}

但是如何將xml shema與JTable、xml一起使用呢?

解決方案

"這里正在寫入 xml 文件:" ---- "這里正在加載我的 xml 文件:"

當您已經在使用 JAXB 映射時,為什么還要使用 DOM 來讀取和寫入 xml.如果您正確地進行映射1,只需使用 <小時>

注意: 使用上面的 JAXB 注釋,您可以創建架構,并且您想針對它驗證 xml,您可以在解組時設置架構.比如:

private static AutoModel unmarshal(String file) throws Exception {JAXBContext 上下文 = JAXBContext.newInstance(AutoModel.class);解組器 unmarshaller = context.createUnmarshaller();SchemaFactory 工廠 = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);Schema schema = factory.newSchema(new File("src/table/autos.xsd"));unmarshaller.setSchema(schema);AutoModel 模型 = (AutoModel)unmarshaller.unmarshal(new File(file));返回模型;}

Here you can see my application:

So what i need to do:

I dont know how I can through code link xml schema with JTable with all type(int,string,float). Say like Year is type int and in schema is int and how i can link it? I dont know how will be in english link or relate. In this application i write all data to xml file, and when application loaded it loads all data from xml file.

Here i creating xml schema:

      public void CreateSchema(String FileName){

        file=FileName;
        JAXBContext jc;
        try {
            jc = JAXBContext.newInstance(XmlSchemaType.class);

                jc.generateSchema(new SchemaOutputResolver() {

                    @Override
                    public javax.xml.transform.Result createOutput(String namespaceURI, String suggestedFileName)throws IOException {
                        suggestedFileName=file+".xsd";
                        return new StreamResult(suggestedFileName);
                    }

                });
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JAXBException e) {
            e.printStackTrace();
        }

  }

Here is all types:

   import javax.xml.bind.annotation.XmlAccessType;
   import javax.xml.bind.annotation.XmlAccessorType;
   import javax.xml.bind.annotation.XmlAttribute;
   import javax.xml.bind.annotation.XmlElement;
   import javax.xml.bind.annotation.XmlRootElement;

   @XmlAccessorType(XmlAccessType.FIELD)
   @XmlRootElement(name = "Auto")
   public class XmlSchemaType {
    row[] Row;
   }


   class row {
    @XmlAttribute
    byte ID;

    @XmlElement
    String VIN;
    @XmlElement
    String Make;
    @XmlElement
    String Model;
    @XmlElement
    int Year;
    @XmlElement
    String Description;
    @XmlElement
    float Cost;
   }

Here is writing to xml file:

public void CreateXml(JTable tb,JTable tb2,String FileName){
      try {

        file=FileName;
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();


        Document doc = docBuilder.newDocument();
        Element rootElement = doc.createElement("Auto");
        doc.appendChild(rootElement);


        int i=0,j=0,k=0;

        while (i<tb.getRowCount()){

            j=0;
            Element rows = doc.createElement("Row");
            rootElement.appendChild(rows);

            Attr attr = doc.createAttribute("id");
            attr.setValue((i+1)+"");
            rows.setAttributeNode(attr);

            //Pirma lentele
            while (j<tb.getColumnCount()-1){

                Element element = doc.createElement(tb.getTableHeader().getColumnModel().getColumn(j).getHeaderValue()+"");
                element.appendChild(doc.createTextNode(tb.getModel().getValueAt(i, j)+""));
                rows.appendChild(element);

                j++;
            }

            //Antra lentele
            j=2;//pirmu lauku nereikia
            while (j<tb2.getColumnCount()-1){
                        Element element2 = doc.createElement(tb2.getTableHeader().getColumnModel().getColumn(j).getHeaderValue()+"");
                        element2.appendChild(doc.createTextNode(tb2.getModel().getValueAt(i, j)+""));
                        rows.appendChild(element2); 
                        if (j==2){
                                tb2.getModel().setValueAt(tb.getModel().getValueAt(i, 0),i,1);  

                        }

                j++;
            }



            i++;
        }

        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result;
        try {
        FileOutputStream fileOutputStream = null;

        fileOutputStream = new FileOutputStream(
                new File(file+".xml"));


        result = new StreamResult(fileOutputStream);//new FileOutputStream(file+".xml"));
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");//new line... kad butu naujoje eiluteje
        transformer.transform(source, result);
        try {
            fileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }


      } catch (ParserConfigurationException pce) {
        pce.printStackTrace();
      } catch (TransformerException tfe) {
        tfe.printStackTrace();
      }
      //file.renameTo(FileName+".xml");

   }

And here loading my xml file:

    public void PopulateDataSet(JTable tb,JTable tb2,String FileName){


      file=FileName;
      File f= new File(file+".xml");
      if (f.exists()){ 
          try {
          DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(f);

            doc.getDocumentElement().normalize();

            NodeList nList = doc.getElementsByTagName("Row");
            for (int temp = 0; temp < nList.getLength(); temp++) {

                Node nNode = nList.item(temp);


                if (nNode.getNodeType() == Node.ELEMENT_NODE) {

                    Element eElement = (Element) nNode;

                    DefaultTableModel model = (DefaultTableModel) tb.getModel();
                    model.addRow(new Object[] { "", "","","","Delete" });
                    tb.getModel().setValueAt(eElement.getElementsByTagName("VIN").item(0).getTextContent(),temp, 0);
                    tb.getModel().setValueAt(eElement.getElementsByTagName("Make").item(0).getTextContent(),temp, 1);
                    tb.getModel().setValueAt(eElement.getElementsByTagName("Make").item(0).getTextContent(),temp, 2);
                    tb.getModel().setValueAt(eElement.getElementsByTagName("Year").item(0).getTextContent(),temp, 3);
                    tb.getModel().setValueAt("Delete",temp, 4);

                    DefaultTableModel model2 = (DefaultTableModel) tb2.getModel();
                    model2.addRow(new Object[] { (tb2.getRowCount()+1), "","","","Delete" });
                     tb2.getModel().setValueAt(eElement.getElementsByTagName("VIN").item(0).getTextContent(),temp, 1);
                    tb2.getModel().setValueAt(eElement.getElementsByTagName("Description").item(0).getTextContent(),temp, 2);
                    tb2.getModel().setValueAt(eElement.getElementsByTagName("Cost").item(0).getTextContent(),temp, 3);
                    tb2.getModel().setValueAt("Delete",temp, 4);

                }

            }

          } catch (Exception e) {
                e.printStackTrace();
                }
      }
      if (!f.exists()){ 
          CreateXml(tb,tb2,file);
          CreateSchema(file); 
      }


  }

But how to use xml shema with JTable, xml?

解決方案

"Here is writing to xml file:" ---- "And here loading my xml file:"

Why are you using DOM to read and write the xml, when you are already using JAXB Mapping. If you are doing the mapping correctly 1, it's just a matter of using the Marshaller and Unmarshaller to write and read, respectively. Make sure to look at those API links yo see example usage. It's only around 5 lines of code to handle each operaion.

(1) Please see the JAXB tutorial for more info about JAXB mapping.

Also, you can just create your own AbstractTableModel and unmarshal and marshal straight to and from the table model. This is probably the most effective way to keep everything sync. Create a class Auto to represent each row, and a class AutoModel, that will be the root element in the xml document, as well as the TableModel for the JTable. Something like:

Auto class

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Auto", propOrder = {
        "id", "VIN", "Make", "Model", "Year", "Description", "Cost"
})
public class Auto {
    @XmlElement(name = "id")
    Integer id;
    @XmlElement(name = "VIN")
    String VIN;
    @XmlElement(name = "Make")
    String Make;
    @XmlElement(name = "Model")
    String Model;
    @XmlElement(name = "Year")
    Integer Year;
    @XmlElement(name = "Description")
    String Description;
    @XmlElement(name = "Cost")
    Float Cost;

    // === DON'T FORGET YOUR GETTERS and SETTERS
}

AutoModel class

@XmlRootElement(name = "AutoList")
public class AutoModel extends AbstractTableModel {
    String[] columnNames = {"VIN", "Make", "Model", "Year"};

    @XmlElement(name = "Auto")
    protected List<Auto> autos;

    public AutoModel() {
        autos = new ArrayList<Auto>();
    }

    @Override
    public int getRowCount() {
        return autos.size();
    }

    @Override
    public int getColumnCount() {
        return columnNames.length;
    }

    @Override
    public String getColumnName(int columnIndex) {
        return columnNames[columnIndex];
    }

    @Override
    public boolean isCellEditable(int row, int col) {
        return false;
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        Auto auto = autos.get(rowIndex);
        Object value = null;
        switch (columnIndex) {
            case 0 : value = auto.getVIN(); break;
            case 1 : value = auto.getMake(); break;
            case 2 : value = auto.getModel(); break;
            case 3 : value = auto.getYear(); break;
        }
        return value;
    }
}

Test, using this xml file

<?xml version="1.0" encoding="UTF-8"?>
<AutoList>
    <Auto>
        <id>1</id>
        <VIN>123456788910FASDE</VIN>
        <Make>Mercedes</Make>
        <Model>CL 550</Model>
        <Year>2012</Year>
        <Description>Hello World</Description>
        <Cost>80000.00</Cost>
    </Auto>
</AutoList>

import java.awt.Dimension;
import java.io.File;
import javax.swing.*;
import javax.xml.bind.*;

public class TestTableMarshall {

    private static final String INPUT_FILE = "src/table/autos.xml";
    private static final String OUTPUT_FILE = "src/table/autos1.xml";

    public static void main(String[] args) throws Exception {
        AutoModel model = unmarshal(INPUT_FILE);
        JTable table = new JTable(model) {
            @Override
            public Dimension getPreferredScrollableViewportSize() {
                return getPreferredSize();
            }
        };
        JOptionPane.showMessageDialog(null, new JScrollPane(table));
        marshal(model, OUTPUT_FILE);

    }

    private static void marshal(AutoModel model, String file) throws Exception {
        JAXBContext context = JAXBContext.newInstance(AutoModel.class);
        Marshaller marshaller = context.createMarshaller();
        File f= new File(file);
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(model, f);
    }

    private static AutoModel unmarshal(String file) throws Exception {
        JAXBContext context = JAXBContext.newInstance(AutoModel.class);
        Unmarshaller unmarshaller = context.createUnmarshaller();
        AutoModel model = (AutoModel)unmarshaller.unmarshal(new File(file));
        return model;
    }
}


As far the the AutoModel goes, it only works for your first table. You will need to create another model for your repairs table. Also, the model, currently only offered read-only. You will need to add other functionality to say add a row and set individual values.

Here are some resources to look at:

  • How to Use Tables: Creating a Table Model
  • JAXB Specification toturial

NOTE: With the JAXB annotations above you can create the schema, and you you want to validate the xml against it, you could just set the schema when you unmarshal. Something like:

private static AutoModel unmarshal(String file) throws Exception {
    JAXBContext context = JAXBContext.newInstance(AutoModel.class);
    Unmarshaller unmarshaller = context.createUnmarshaller();
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = factory.newSchema(new File("src/table/autos.xsd"));
    unmarshaller.setSchema(schema);
    AutoModel model = (AutoModel)unmarshaller.unmarshal(new File(file));
    return model;
}

這篇關于如何使 xml 模式與 JTable、xml java 相關(鏈接)?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!

【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!

相關文檔推薦

How to wrap text around components in a JTextPane?(如何在 JTextPane 中的組件周圍環繞文本?)
MyBatis, how to get the auto generated key of an insert? [MySql](MyBatis,如何獲取插入的自動生成密鑰?[MySql])
Inserting to Oracle Nested Table in Java(在 Java 中插入 Oracle 嵌套表)
Java: How to insert CLOB into oracle database(Java:如何將 CLOB 插入 oracle 數據庫)
Why does Spring-data-jdbc not save my Car object?(為什么 Spring-data-jdbc 不保存我的 Car 對象?)
Use threading to process file chunk by chunk(使用線程逐塊處理文件)
主站蜘蛛池模板: 单锥双螺旋混合机_双螺旋锥形混合机-无锡新洋设备科技有限公司 | 东莞螺杆空压机_永磁变频空压机_节能空压机_空压机工厂批发_深圳螺杆空压机_广州螺杆空压机_东莞空压机_空压机批发_东莞空压机工厂批发_东莞市文颖设备科技有限公司 | 宁夏活性炭_防护活性炭_催化剂载体炭-宁夏恒辉活性炭有限公司 | 贴片电容代理-三星电容-村田电容-风华电容-国巨电容-深圳市昂洋科技有限公司 | 网架支座@球铰支座@钢结构支座@成品支座厂家@万向滑动支座_桥兴工程橡胶有限公司 | 空气能暖气片,暖气片厂家,山东暖气片,临沂暖气片-临沂永超暖通设备有限公司 | 金属抛光机-磁悬浮抛光机-磁力研磨机-磁力清洗机 - 苏州冠古科技 | 清管器,管道清管器,聚氨酯发泡球,清管球 - 承德嘉拓设备 | 餐饮加盟网_特色餐饮加盟店_餐饮连锁店加盟| 自动检重秤-动态称重机-重量分选秤-苏州金钻称重设备系统开发有限公司 | 实体店商新零售|微赢|波后|波后合作|微赢集团| 上海网站建设-上海网站制作-上海网站设计-上海做网站公司-咏熠软件 | 新疆系统集成_新疆系统集成公司_系统集成项目-新疆利成科技 | 商秀—企业短视频代运营_抖音企业号托管 | 海外仓系统|国际货代系统|退货换标系统|WMS仓储系统|海豚云 | 北京遮阳网-防尘盖土网-盖土草坪-迷彩网-防尘网生产厂家-京兴科技 | 挤奶设备过滤纸,牛奶过滤纸,挤奶机过滤袋-济南蓝贝尔工贸有限公司 | 镀锌钢格栅_热镀锌格栅板_钢格栅板_热镀锌钢格板-安平县昊泽丝网制品有限公司 | 柔性测斜仪_滑动测斜仪-广州杰芯科技有限公司 | FAG轴承,苏州FAG轴承,德国FAG轴承-恩梯必传动设备(苏州)有限公司 | 帽子厂家_帽子工厂_帽子定做_义乌帽厂_帽厂_制帽厂_帽子厂_浙江高普制帽厂 | 国产离子色谱仪,红外分光测油仪,自动烟尘烟气测试仪-青岛埃仑通用科技有限公司 | 运动木地板_体育木地板_篮球馆木地板_舞台木地板-实木运动地板厂家 | 数显恒温油浴-电砂浴-高温油浴振荡器-常州迈科诺仪器有限公司 | 烟台游艇培训,威海游艇培训-烟台市邮轮游艇行业协会 | China plate rolling machine manufacturer,cone rolling machine-Saint Fighter | 儋州在线-儋州招聘找工作、找房子、找对象,儋州综合生活信息门户! | 世界箱包品牌十大排名,女包小众轻奢品牌推荐200元左右,男包十大奢侈品牌排行榜双肩,学生拉杆箱什么品牌好质量好 - Gouwu3.com | 冲击式破碎机-冲击式制砂机-移动碎石机厂家_青州市富康机械有限公司 | 高温热泵烘干机,高温烘干热泵,热水设备机组_正旭热泵 | 培训中心-海南香蕉蛋糕加盟店技术翰香原中心官网总部 | TPE塑胶原料-PPA|杜邦pom工程塑料、PPSU|PCTG材料、PC/PBT价格-悦诚塑胶 | 除湿机|工业除湿机|抽湿器|大型地下室车间仓库吊顶防爆除湿机|抽湿烘干房|新风除湿机|调温/降温除湿机|恒温恒湿机|加湿机-杭州川田电器有限公司 | 学习虾-免费的学习资料下载平台| 日本SMC气缸接头-速度控制阀-日本三菱伺服电机-苏州禾力自动化科技有限公司 | 中宏网-今日新闻-财经新闻| 成都治疗尖锐湿疣比较好的医院-成都治疗尖锐湿疣那家医院好-成都西南皮肤病医院 | 阀门智能定位器_电液动执行器_气动执行机构-赫尔法流体技术(北京)有限公司 | 车牌识别道闸_停车场收费系统_人脸识别考勤机_速通门闸机_充电桩厂家_中全清茂官网 | 体视显微镜_荧光生物显微镜_显微镜报价-微仪光电生命科学显微镜有限公司 | 超高频感应加热设备_高频感应电源厂家_CCD视觉检测设备_振动盘视觉检测设备_深圳雨滴科技-深圳市雨滴科技有限公司 |