xml验证:发现以元素开头的无效内容

z8dt9xmd  于 2021-06-30  发布在  Java
关注(0)|答案(2)|浏览(412)

我的xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<workbook xmlns="http://www.dei.isep.ipp.pt/lapr4" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.dei.isep.ipp.pt/lapr4 validate.xsd">
<lastSave>2013/06/05 20:33:23</lastSave>
<numSpreadsheets>3</numSpreadsheets>
<spreadsheet title="Sheet  1">
<cell horizAlign="2" vertiAlign="0" fontStyle="0" fontSize="12" fontName="Dialog" fgColor="-13421773" bgColor="-1" left="1" right="1" top="1" bottom="1" content="a" address="C7" row="6" column="2"/>
<cell horizAlign="2" vertiAlign="0" fontStyle="0" fontSize="12" fontName="Dialog" fgColor="-13421773" bgColor="-1" left="1" right="1" top="1" bottom="1" content="asd" address="A7" row="6" column="0"/>
<cell horizAlign="2" vertiAlign="0" fontStyle="0" fontSize="12" fontName="Dialog" fgColor="-13421773" bgColor="-1" left="1" right="1" top="1" bottom="1" content="ad" address="B5" row="4" column="1"/>
<cell horizAlign="2" vertiAlign="0" fontStyle="0" fontSize="12" fontName="Dialog" fgColor="-13421773" bgColor="-1" left="1" right="1" top="1" bottom="1" content="sad" address="B7" row="6" column="1"/>
</spreadsheet>
<spreadsheet title="Sheet  2"/>
<spreadsheet title="Sheet  3"/>
</workbook>

我的xsd文件:

<?xml version="1.0" encoding="UTF-8"?>

<xs:schema xmlns="http://www.dei.isep.ipp.pt/lapr4" 
           xmlns:xs="http://www.w3.org/2001/XMLSchema"
           targetNamespace="http://www.dei.isep.ipp.pt/lapr4"
           elementFormDefault="qualified">

    <xs:element name="workbook" type="TWorkbook"/>

</xs:schema>
<xs:complexType name="TWorkbook">
    <xs:sequence>
        <xs:element name="lastSave" type="xs:string"/>
        <xs:element name="numSpreadsheets" type="TnumSpreadsheets" minOccurs="1"/>
        <xs:element name="spreadsheet" type="TSpreadSheet" maxOccurs="unbounded"/>
    </xs:sequence>
</xs:complexType>

<xs:simpleType name="TnumSpreadsheets">
    <xs:restriction base="xs:int">
        <xs:minInclusive value="0"/>
        <xs:maxInclusive value="100" />
    </xs:restriction>
</xs:simpleType>

<xs:complexType name="TSpreadSheet">
    <xs:sequence>
        <xs:element name="cell" type="TCell"  maxOccurs="unbounded"/>
    </xs:sequence>
    <xs:attribute name="title" type="xs:string" /> 
</xs:complexType>    

<xs:complexType name="TCell">
    <xs:attribute name="row" type="xs:int" />
    <xs:attribute  name="column" type="xs:int" />

    <xs:attribute  name="horizAlign" type="xs:int" />
    <xs:attribute  name="vertiAlign" type="xs:int" />

    <xs:attribute  name="fontStyle" type="xs:int" />
    <xs:attribute  name="fontSize" type="xs:int" />
    <xs:attribute  name="font" type="xs:string" />
    <xs:attribute  name="address" type="xs:string" />
    <xs:attribute  name="fontName" type="xs:string" />
    <xs:attribute  name="fgColor" type="xs:int" />
    <xs:attribute  name="bgColor" type="xs:int" />

    <xs:attribute  name="left" type="xs:int" />
    <xs:attribute  name="right" type="xs:int" />
    <xs:attribute  name="top" type="xs:int" />
    <xs:attribute  name="bottom" type="xs:int" />

    <xs:attribute  name="content" type="xs:string" />
</xs:complexType>      

</xs:schema>

我一个接一个地验证了文件,并在web和netbeans上相互验证,但当我运行应用程序时,总是出现以下错误:
org.xml.sax.saxparseexception:cvc复杂类型.2.4.a:发现以元素“lastsave”开头的无效内容。“{”之一http://www.dei.isep.ipp.pt/lapr4应为“:numspreadsheets}”。
我一直在寻找答案,但似乎没有任何工作,有人能给我一些关于这个问题的灯?
提前谢谢。

ykejflvf

ykejflvf1#

@mifet这是我用来创建xml文件的java文件:

package csheets.io;

import csheets.core.Cell;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import csheets.core.Spreadsheet;
import csheets.core.Workbook;
import csheets.ext.style.StylableCell;
import csheets.ext.style.StyleExtension;
import java.awt.Color;
import java.awt.Font;
import java.io.File;
import java.io.StringWriter;
import java.io.Writer;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import javax.swing.BorderFactory;
import javax.swing.border.Border;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamResult;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;

/**
 * A codec for XML files.
 *
 * @author Cristiano
 */
public class XMLCodec implements Codec {

    String xml;
    private String keyWrite;

    public XMLCodec() {
    }
    /*Metodo read, lê de um ficheiro XML, valida o ficheiro com o seu XSD 
     * correspondete e por fim preenche as celulas da spreadsheet com a 
     * informação contida no XML
     * return Workbook;*/

    public Workbook read(InputStream stream) throws IOException {
        Workbook work = null;
        try {
            work = new Workbook();
            int temp = 0;
            Node nNode;
            Element eElement = null;
            StylableCell stylableCell;

            /*Criação do documento*/
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            dbFactory.setValidating(false);
            dbFactory.setNamespaceAware(true);
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(stream);

            /*Validação do documento XML*/
            Schema sch = carregarSchema("validate.xsd");
            if (validarXml(sch, doc)) {
                doc.getDocumentElement().normalize();

                NodeList nList = doc.getElementsByTagName("workbook");
                nNode = nList.item(temp);
                eElement = (Element) nNode;

                nList = doc.getElementsByTagName("spreadsheet");
                for (temp = 0; temp < nList.getLength(); temp++) {
                    nNode = nList.item(temp);
                    if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                        eElement = (Element) nNode;
                        String spreadTitle = eElement.getAttribute("title");
                        work.addSpreadsheet();
                        work.getSpreadsheet(temp).setTitle(spreadTitle);

                        NodeList nListCells = eElement.getElementsByTagName("cell");
                        int numCellsOnSpread = eElement.getElementsByTagName("cell").getLength();
                        for (int k = 0; k < numCellsOnSpread; k++) {
                            Node nNodeCell = nListCells.item(k);
                            Element eElementCell = (Element) nNodeCell;

                            String row = eElementCell.getAttribute("row");
                            String column = eElementCell.getAttribute("column");
                            String horizAlign = eElementCell.getAttribute("horizAlign");
                            String vertiAlign = eElementCell.getAttribute("vertiAlign");
                            String fontStyle = eElementCell.getAttribute("fontStyle");
                            String fontSize = eElementCell.getAttribute("fontSize");
                            String fontName = eElementCell.getAttribute("fontName");
                            String fgColor = eElementCell.getAttribute("fgColor");
                            String bgColor = eElementCell.getAttribute("bgColor");
                            String left = eElementCell.getAttribute("left");
                            String right = eElementCell.getAttribute("right");
                            String top = eElementCell.getAttribute("top");
                            String bottom = eElementCell.getAttribute("bottom");
                            String content = eElementCell.getAttribute("content");

                            int columnInt = Integer.parseInt(column);
                            int rowInt = Integer.parseInt(row);
                            stylableCell = (StylableCell) work.getSpreadsheet(temp).getCell(columnInt, rowInt).getExtension(StyleExtension.NAME);

                            stylableCell.setHorizontalAlignment(Integer.parseInt(horizAlign));
                            stylableCell.setVerticalAlignment(Integer.parseInt(vertiAlign));
                            Font font = new Font(fontName, Integer.parseInt(fontStyle), Integer.parseInt(fontSize));
                            stylableCell.setFont(font);
                            Color fgCol = new Color(Integer.parseInt(fgColor));
                            stylableCell.setForegroundColor(fgCol);
                            Color bgCol = new Color(Integer.parseInt(bgColor));
                            stylableCell.setBackgroundColor(bgCol);
                            Border cellBord = BorderFactory.createMatteBorder(Integer.parseInt(top), Integer.parseInt(left), Integer.parseInt(bottom), Integer.parseInt(right), Color.darkGray);
                            stylableCell.setBorder(cellBord);
                            stylableCell.setContent(content);
                        }

                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        work = new Workbook(3);
        return work;
    }
    /*Metodo write, recebe um Workbook e OutputStream, cria um ficheiro XML com
     * a informação contida nas celulas da spreadsheet*/

    public void write(Workbook workbook, OutputStream stream) {
        xml = null;
        keyWrite = null;
        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        Date date = new Date();
        String dataHora = dateFormat.format(date);

        Writer writer = new StringWriter();
        StreamResult strResult = new StreamResult(writer);
        SAXTransformerFactory transFactory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();

        TransformerHandler transHandler = null;
        try {
            transHandler = transFactory.newTransformerHandler();
        } catch (TransformerConfigurationException ex) {
            ex.getMessage();
        }

        Transformer serializer = transHandler.getTransformer();
        serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        serializer.setOutputProperty(OutputKeys.INDENT, "yes");
        transHandler.setResult(strResult);

        try {
            transHandler.startDocument();
        } catch (SAXException ex) {
            ex.getMessage();
        }

        AttributesImpl attributes = new AttributesImpl();

        // <workbook>
        try {
            attributes.clear();
            attributes.addAttribute("", "", "xmlns", "CDATA", "http://www.dei.isep.ipp.pt/lapr4");
            attributes.addAttribute("", "", "xmlns:xsi", "CDATA", "http://www.w3.org/2001/XMLSchema-instance");
            attributes.addAttribute("", "", "xsi:schemaLocation", "CDATA", "http://www.dei.isep.ipp.pt/lapr4 validate.xsd");
            transHandler.startElement("", "", "workbook", attributes);
        } catch (SAXException ex) {
            ex.getMessage();
        }

        // <lastSave>
        try {
            attributes.clear();
            transHandler.startElement("", "", "lastSave", attributes);
            transHandler.characters(dataHora.toCharArray(), 0, dataHora.length());
            transHandler.endElement("", "", "lastSave");
        } catch (SAXException ex) {
            ex.getMessage();
        }

        // <numSpreadsheets>
        try {
            attributes.clear();
            transHandler.startElement("", "", "numSpreadsheets", attributes);
            String numSheets = "" + workbook.getSpreadsheetCount();
            transHandler.characters(numSheets.toCharArray(), 0, numSheets.length());
            transHandler.endElement("", "", "numSpreadsheets");
        } catch (SAXException ex) {
            ex.getMessage();
        }

        Iterator<Spreadsheet> sheetsIterator = workbook.iterator(); //iterador paras as sheets

        while (sheetsIterator.hasNext()) { //enquanto existirem sheets
            Spreadsheet sheet = sheetsIterator.next(); //para cada sheet

            // <spreadsheet>
            try {
                attributes.clear();
                attributes.addAttribute("", "", "title", "CDATA", sheet.getTitle()); // <spreadsheet title="">
                transHandler.startElement("", "", "spreadsheet", attributes);
            } catch (SAXException ex) {
                ex.getMessage();
            }

            Iterator<Cell> cellIterator = sheet.iterator(); //iterador para cells
            while (cellIterator.hasNext()) { //enquanto houver cells
                Cell cell = cellIterator.next(); //para cada cell

                // <cell>
                try {
                    if (!cell.getContent().equals("")) { //se não vazia
                        StylableCell stylableCell = (StylableCell) cell.getExtension(StyleExtension.NAME);

                        attributes.clear();

                        String horizAlign = "" + stylableCell.getHorizontalAlignment(); // alinhamento horizontal
                        attributes.addAttribute("", "", "horizAlign", "CDATA", horizAlign);

                        String vertiAlign = "" + stylableCell.getVerticalAlignment(); // alinhamento vertical
                        attributes.addAttribute("", "", "vertiAlign", "CDATA", vertiAlign);

                        // letra da cell
                        String fontStyle = "" + stylableCell.getFont().getStyle(); // style
                        attributes.addAttribute("", "", "fontStyle", "CDATA", fontStyle);

                        String fontSize = "" + stylableCell.getFont().getSize(); // size
                        attributes.addAttribute("", "", "fontSize", "CDATA", fontSize);

                        String fontName = "" + stylableCell.getFont().getName(); // font name
                        attributes.addAttribute("", "", "fontName", "CDATA", fontName);

                        String foregColor = "" + stylableCell.getForegroundColor().getRGB(); // foreground color
                        attributes.addAttribute("", "", "fgColor", "CDATA", foregColor);

                        String backgColor = "" + stylableCell.getBackgroundColor().getRGB(); // background color
                        attributes.addAttribute("", "", "bgColor", "CDATA", backgColor);

                        // bordas da cell
                        String left = "" + stylableCell.getBorder().getBorderInsets(null).left; // xml left
                        attributes.addAttribute("", "", "left", "CDATA", left);

                        String right = "" + stylableCell.getBorder().getBorderInsets(null).right; // xml right
                        attributes.addAttribute("", "", "right", "CDATA", right);

                        String top = "" + stylableCell.getBorder().getBorderInsets(null).top; // xml top
                        attributes.addAttribute("", "", "top", "CDATA", top);

                        String bottom = "" + stylableCell.getBorder().getBorderInsets(null).bottom; // xml bottom
                        attributes.addAttribute("", "", "bottom", "CDATA", bottom);

                        String content = "" + cell.getContent(); // conteudo da célula
                        attributes.addAttribute("", "", "content", "CDATA", content);

                        String address = "" + cell.getAddress(); //address
                        attributes.addAttribute("", "", "address", "CDATA", address);

                        String row = "" + cell.getAddress().getRow(); // linhas
                        attributes.addAttribute("", "", "row", "CDATA", row);

                        String column = "" + cell.getAddress().getColumn(); // colunas
                        attributes.addAttribute("", "", "column", "CDATA", column);

                        transHandler.startElement("", "", "cell", attributes); //<cell>
                        transHandler.endElement("", "", "cell"); //</cell>
                    }
                } catch (SAXException ex) {
                    ex.getMessage();
                }
            }

            try {
                transHandler.endElement("", "", "spreadsheet"); //</spreadsheet>
            } catch (SAXException ex) {
                ex.getMessage();
            }

        }
        try {
            transHandler.endElement("", "", "workbook"); //</workbook>
            transHandler.endDocument(); //fim documento
            writer.close();
        } catch (SAXException sasex) {
            sasex.getMessage();
        } catch (IOException ex) {
            ex.getMessage();
        }

        StringWriter strWriter = (StringWriter) strResult.getWriter();
        StringBuffer strBuffer = strWriter.getBuffer();
        String xmlDoc = strBuffer.toString();

        /*Escreve o ficheiro XML*/
        PrintWriter printWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(stream)));
        printWriter.write(xmlDoc);
        printWriter.close();

        this.xml = xmlDoc;
        System.out.println("Gravado com sucesso!");
    }
    /*Metodo carregarSchema, recebe uma string com o nome do ficheiro XSD 
     * que pretende carregar.
     * return Schema;*/

    private static Schema carregarSchema(String name) {
        Schema s = null;
        try {
            String lang = XMLConstants.W3C_XML_SCHEMA_NS_URI;
            SchemaFactory factory = SchemaFactory.newInstance(lang);

            s = factory.newSchema(new File(name));
        } catch (Exception e) {
            System.out.println(e.toString());
        }
        return s;
    }
    /*Metodo validarXml, recebe um Schema e um Document e valida 
     * o ficheiro XML com o XSD correspondente*/

    private static boolean validarXml(Schema schema, Document document) {
        try {
            Validator valida = schema.newValidator();
            valida.validate(new DOMSource(document));
            System.out.println("Validação efectuada com sucesso!");
            return true;
        } catch (Exception ex) {
            System.out.println("Validação encontrou erros! Ficheiro defeituoso.");
            System.out.println(ex.toString());
            return false;
        }
    }
}

我是葡萄牙人,所以这里写的一些东西是葡萄牙语的

l7mqbcuq

l7mqbcuq2#

你有两倍的时间 </xs:schema> xsd文件中的结束标记。尝试删除第一个出现的问题,它会使xsd处理器混淆。
而且,你还错过了一个 <cell /> 中的元素 <spreadsheet /> 标签添加底部。
这验证了所有权利:
xml格式:

<?xml version="1.0" encoding="UTF-8"?>
<workbook xmlns="http://www.dei.isep.ipp.pt/lapr4" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.dei.isep.ipp.pt/lapr4 validate.xsd">
    <lastSave>2013/06/05 20:33:23</lastSave>
    <numSpreadsheets>3</numSpreadsheets>
    <spreadsheet title="Sheet  1">
        <cell horizAlign="2" vertiAlign="0" fontStyle="0" fontSize="12" fontName="Dialog" fgColor="-13421773" bgColor="-1" left="1" right="1" top="1" bottom="1" content="a" address="C7" row="6" column="2"/>
        <cell horizAlign="2" vertiAlign="0" fontStyle="0" fontSize="12" fontName="Dialog" fgColor="-13421773" bgColor="-1" left="1" right="1" top="1" bottom="1" content="asd" address="A7" row="6" column="0"/>
        <cell horizAlign="2" vertiAlign="0" fontStyle="0" fontSize="12" fontName="Dialog" fgColor="-13421773" bgColor="-1" left="1" right="1" top="1" bottom="1" content="ad" address="B5" row="4" column="1"/>
        <cell horizAlign="2" vertiAlign="0" fontStyle="0" fontSize="12" fontName="Dialog" fgColor="-13421773" bgColor="-1" left="1" right="1" top="1" bottom="1" content="sad" address="B7" row="6" column="1"/>
    </spreadsheet>
    <spreadsheet title="Sheet  2"><cell /></spreadsheet>
    <spreadsheet title="Sheet  2"><cell /></spreadsheet>
</workbook>

xsd码:

<?xml version="1.0" encoding="UTF-8"?>

<xs:schema xmlns="http://www.dei.isep.ipp.pt/lapr4" 
           xmlns:xs="http://www.w3.org/2001/XMLSchema"
           targetNamespace="http://www.dei.isep.ipp.pt/lapr4"
           elementFormDefault="qualified">

    <xs:element name="workbook" type="TWorkbook"/>

<xs:complexType name="TWorkbook">
    <xs:sequence>
        <xs:element name="lastSave" type="xs:string"/>
        <xs:element name="numSpreadsheets" type="TnumSpreadsheets" minOccurs="1"/>
        <xs:element name="spreadsheet" type="TSpreadSheet" maxOccurs="unbounded"/>
    </xs:sequence>
</xs:complexType>

<xs:simpleType name="TnumSpreadsheets">
    <xs:restriction base="xs:int">
        <xs:minInclusive value="0"/>
        <xs:maxInclusive value="100" />
    </xs:restriction>
</xs:simpleType>

<xs:complexType name="TSpreadSheet">
    <xs:sequence>
        <xs:element name="cell" type="TCell"  maxOccurs="unbounded"/>
    </xs:sequence>
    <xs:attribute name="title" type="xs:string" /> 
</xs:complexType>    

<xs:complexType name="TCell">
    <xs:attribute name="row" type="xs:int" />
    <xs:attribute  name="column" type="xs:int" />

    <xs:attribute  name="horizAlign" type="xs:int" />
    <xs:attribute  name="vertiAlign" type="xs:int" />

    <xs:attribute  name="fontStyle" type="xs:int" />
    <xs:attribute  name="fontSize" type="xs:int" />
    <xs:attribute  name="font" type="xs:string" />
    <xs:attribute  name="address" type="xs:string" />
    <xs:attribute  name="fontName" type="xs:string" />
    <xs:attribute  name="fgColor" type="xs:int" />
    <xs:attribute  name="bgColor" type="xs:int" />

    <xs:attribute  name="left" type="xs:int" />
    <xs:attribute  name="right" type="xs:int" />
    <xs:attribute  name="top" type="xs:int" />
    <xs:attribute  name="bottom" type="xs:int" />

    <xs:attribute  name="content" type="xs:string" />
</xs:complexType>      

</xs:schema>

相关问题