I managed to root out the cause of this error in my program:

INVALID_CHARACTER_ERR: An invalid or illegal XML character is specified.

I did a test app to ensure that the cause is correct.

Test Code:

    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();

When I removed the leading number in 2TEST, it works fine, the leading number is needed in some of the entries and cannot be eliminated, are there any workaround in this situation?

有帮助吗?

解决方案

XML tag name cannot start with a digit. From 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]

So you need to manually escape character somehow before using it as a first character in tag name. For example, you can use underscore character if you don't have normal tags starting with it.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top