gpt4 book ai didi

java - 在java中写入XML文件时出错

转载 作者:行者123 更新时间:2023-11-30 07:50:44 33 4
gpt4 key购买 nike

我正在尝试使用 Java 编写一个 xml 文件,并且想将变量字符串发送到方法 document.createElement(var) ,但它给了我这个错误:

"Exception in thread "main" org.w3c.dom.DOMException: INVALID_CHARACTER_ERR: An invalid or illegal XML character is specified. 
at com.sun.org.apache.xerces.internal.dom.CoreDocumentImpl.createElement(Unknown Source)
at eg.edu.alexu.csd.oop.draw.WriteXML.<init>(WriteXML.java:47)
at eg.edu.alexu.csd.oop.draw.Test.main(Test.java:25)"

这个错误是因为 var 是一个变量

public class WriteXML {

public WriteXML() throws FileNotFoundException, ParserConfigurationException, IOException{
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document xmlDoc = docBuilder.newDocument();
for(int i=0 ; i<shapes.length ; i++){
//class
s = shapes[i].getClass().getName().toString();
Element rootElement = xmlDoc.createElement(s);
}

最佳答案

数字不能用作标签名称。这是一个简化的测试:

// Generates the error
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document xmlDoc = docBuilder.newDocument();
xmlDoc.createElement("0");

您可以使用属性或文本内容来设置数字。

DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document xmlDoc = docBuilder.newDocument();
xmlDoc.createElement("Red").setTextContent("0");

XML Specification

我不确定,但我认为相关行是:

[Definition: A Name is an Nmtoken with a restricted set of initial characters.] Disallowed initial characters for Names include digits, diacritics, the full stop and the hyphen.

关于java - 在java中写入XML文件时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33376019/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com