Java 我在尝试创建 XML 文件时不断出错

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22440902/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 15:44:15  来源:igfitidea点击:

I keep getting error while trying to create an XML file

javaxmldom

提问by Jpfcan

I just keep getting this error after some time working on it, i had an error before that just disappeared and now I get this one:

经过一段时间的工作后,我一直收到此错误,在此之前我有一个错误消失了,现在我得到了这个错误:

Exception in thread "main" org.w3c.dom.DOMException: INVALID_CHARACTER_ERR: An invalid             or illegal XML character is specified. 

at org.apache.xerces.dom.CoreDocumentImpl.createAttribute(Unknown Source)
at org.apache.xerces.dom.ElementImpl.setAttribute(Unknown Source)
at creandoXML2.CreaDOM.createEmpleadoElement(CreaDOM.java:91)
at creandoXML2.CreaDOM.createDOMTree(CreaDOM.java:84)
at creandoXML2.CreaDOM.<init>(CreaDOM.java:47)
at creandoXML2.CreaDOM.main(CreaDOM.java:33)
Java Result: 1"

I've reviewed my code several time but it just doesn't work,can anyone help me? here′s the code:

我已经多次查看我的代码,但它不起作用,有人可以帮助我吗?这是代码:

package creandoXML2;

import com.sun.org.apache.xml.internal.serialize.OutputFormat;
import com.sun.org.apache.xml.internal.serialize.XMLSerializer;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;

/**
 *
 * @author Juan Pablo
 */
public class CreaDOM {
    private List myData;
    private Document dom;
    private String rutaArchivo;


    public static void main(String[] args) {
        new CreaDOM();
    }

    public CreaDOM(){
        this.dom=null;
        this.rutaArchivo="./Archivos/";

        myData=new ArrayList();

        this.loadData();

        this.createDocument();

        this.createDOMTree();

        this.printToFile();
    }

    private void loadData(){
        myData.add(new Empleado("123","Luis Sierra","20","Prestación"));
        myData.add(new Empleado("234","Kathy Fuquen","23","Temporal"));
        myData.add(new Empleado("345","L. Miguel Beltrán","22","Permanente"));
        myData.add(new Empleado("456","Juan Pablo Fajardo Cano","19","Temporal"));
    }

    private void createDocument(){
        DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
        try{

            DocumentBuilder db=dbf.newDocumentBuilder();

            dom=db.newDocument();
        }
        catch(ParserConfigurationException pce){
            System.out.println("Error while trying to instantiate DocumentBuilder");
            System.exit(1);
        }
    }

    private void createDOMTree(){

        Element rootEle=dom.createElement("Personnel");
        dom.appendChild(rootEle);


        Iterator it=myData.iterator();
        while(it.hasNext()){
            Empleado e=(Empleado)it.next();

            Element empleadoEle=createEmpleadoElement(e);
            rootEle.appendChild(empleadoEle);
        }
    }

    private Element createEmpleadoElement(Empleado e){
        Element empleadoEle=dom.createElement("Empleado");
        empleadoEle.setAttribute("Tipo de empleado: ",e.getTipoEmp());

        Element nomEle=dom.createElement("Nombre");
        Text nomText=dom.createTextNode(e.getName());
        nomEle.appendChild(nomText);
        empleadoEle.appendChild(nomEle);

        Element idEle=dom.createElement("ID");
        Text idText=dom.createTextNode(e.getId());
        idEle.appendChild(idText);
        empleadoEle.appendChild(idEle);

        Element ageEle=dom.createElement("Edad");
        Text ageText=dom.createTextNode(e.getAge());
        ageEle.appendChild(ageText);
        empleadoEle.appendChild(ageEle);

        return empleadoEle;
    }

    private void printToFile(){
        try{
            OutputFormat format=new OutputFormat(dom);
            format.setIndenting(true);


            File file=new File(rutaArchivo+"Empleados.xml");
            FileOutputStream fos=new FileOutputStream(file);
            XMLSerializer serializer=new XMLSerializer(fos,format);

            serializer.serialize(dom);
            System.out.println("It's OK...file generated successfully!");
        }
        catch(IOException ie){
            System.out.println("Error generando archivo!...."+ie);
        }
    }
}

Here′s the Empleado Class:

这是 Empleado 类:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package creandoXML2;

/**
 *
 * @author Juan Pablo
 */
public class Empleado {

    private String id;
    private String name;
    private String age;
    private String tipoEmp;

    public Empleado() {
        this.id="";
        this.name="";
        this.age="";
        this.tipoEmp="";                
    }

    public Empleado(String id, String name, String age, String tipoEmp) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.tipoEmp = tipoEmp;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    public String getTipoEmp() {
        return tipoEmp;
    }

    public void setTipoEmp(String tipoEmp) {
        this.tipoEmp = tipoEmp;
    }

    @Override
    public String toString() {
        String datos=this.name+","+this.id+","+this.age+","+this.tipoEmp;
        return datos;
    }    
}

采纳答案by Reimeus

If you take a look in the allowed XML Attribute name characters, you'll see that spaces are in fact not present so are illegal

如果您查看允许的XML 属性名称字符,您会发现实际上不存在空格,因此是非法的

so instead of

所以而不是

empleadoEle.setAttribute("Tipo de empleado: ", e.getTipoEmp());

You could do

你可以做

empleadoEle.setAttribute("tipo", e.getTipoEmp());

回答by user2532244

I know this is resolved. In my case, I was using a function to modify my xpaths for both reading and writing a value.

我知道这已经解决了。就我而言,我使用一个函数来修改我的 xpaths 以读取和写入值。

I didn't realize its adding /text() in my xpath so I was getting this error while inserting a node

我没有意识到它在我的 xpath 中添加了 /text() 所以我在插入节点时遇到了这个错误