【问题标题】:Java document createElement errorJava 文档 createElement 错误
【发布时间】:2014-01-28 16:51:09
【问题描述】:

我设法在我的程序中根除此错误的原因:

INVALID_CHARACTER_ERR:指定了无效或非法的 XML 字符。

我做了一个测试应用来确保原因是正确的。

测试代码:

    String x = "2TEST";  // <--------- when there is no leading number
                                 //          app executes normally

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder;
    try {
        builder = factory.newDocumentBuilder();
        Document doc = builder.newDocument();

        doc.createElement(x);
    } catch (ParserConfigurationException e) {
        e.printStackTrace();

当我在 2TEST 中删除前导数字时,它工作正常,某些条目中需要前导数字并且无法消除,这种情况有什么解决方法吗?

【问题讨论】:

    标签: java xml document


    【解决方案1】:

    XML 标记名称不能以数字开头。来自spec

    The first character of a Name must be a NameStartChar
    
    NameStartChar ::= ":" | [A-Z] | "_" | [a-z] | [#xC0-#xD6] |
                      [#xD8-#xF6] | [#xF8-#x2FF] | [#x370-#x37D] |
                      [#x37F-#x1FFF] | [#x200C-#x200D] | [#x2070-#x218F] |
                      [#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF] |
                      [#xFDF0-#xFFFD] | [#x10000-#xEFFFF]
    

    因此,在将其用作标记名称中的第一个字符之前,您需要以某种方式手动转义字符。例如,如果您没有以它开头的普通标签,则可以使用下划线字符。

    【讨论】:

    • 谢谢,我做了一个方法,当它有前导数字时会添加下划线“_”。
    猜你喜欢
    • 2013-01-11
    • 1970-01-01
    • 1970-01-01
    • 2019-06-15
    • 2018-12-22
    • 2021-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多