2016-04-29 55 views
0

添加一個新的屬性如何添加在XML頭標記一個新的屬性一樣如何在XML頭標記在DOM4J

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

我需要增加新屬性「text1

目前它的下面創造時尚

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

如果你需要* *添加這樣的事情,你的XML規範之外。使用另一種工具。 –

回答

0

簡單的答案是你不能和你不應該。否則,你正在破壞XML的良構...

0

你可以擴展XMLWriter並覆蓋writeDeclaration方法來添加屬性。

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

結果

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