如何在DOM4J的XML头标记中添加新属性

时间:2016-04-29 09:46:45

标签: xml dom4j

如何在XML标头标签中添加新属性,如

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

我需要添加新属性&#34; text1&#34;

目前它以下面的方式创作

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

2 个答案:

答案 0 :(得分:0)

简单的答案是你做不到而且你不应该这样做。否则,你正在破坏XML的良好结构......

答案 1 :(得分:0)

您可以扩展XMLWriter并覆盖writeDeclaration方法以添加属性。

Visitor_id  P_id    Age NumVisits
   10        1       0     2
   10        2       1     1
   11        2       1     1
   11        4       2     1
   12        3       2     1

结果

@Override
protected void writeDeclaration() throws IOException {
    OutputFormat format = getOutputFormat();
    String encoding = format.getEncoding();

    // Only print of declaration is not suppressed
    if (!format.isSuppressDeclaration()) {
        // Assume 1.0 version
        if (encoding.equals("UTF8")) {
            writer.write("<?xml version=\"1.0\"");

            if (!format.isOmitEncoding()) {
                writer.write(" encoding=\"UTF-8\"");
            }

            // TODO Add your attribute hear
            writer.write(" standalone=\"yes\"");

            writer.write("?>");
        } else {
            writer.write("<?xml version=\"1.0\"");

            if (!format.isOmitEncoding()) {
                writer.write(" encoding=\"" + encoding + "\"");
            }

            // TODO Add your attribute hear
            writer.write(" standalone=\"yes\"");

            writer.write("?>");
        }

        if (format.isNewLineAfterDeclaration()) {
            println();
        }
    }
}