日期:2014-05-20  浏览次数:20785 次

java代码怎么向xml文件中添加多个注释?
本帖最后由 u013156418 于 2014-02-20 12:42:51 编辑
我需要创建一个带注释的xml文件,已知:注释内容有了,xml文本内容也有了(不需要创建xml节点),路径也知道。我的想法是写一个方法,类似于writeToXml(String log,String xml,String filePath)
最终结果的应该是这样的:
<?xml version="1.0" encoding="UTF-8"?>
<!--
########################################
@ FileName:test.xml
@ Date:2014-02-20  10:24:24
@ Editor:Kobe
@ Version:1.0.0
@ Log:这是一个测试文件
########################################
-->
<!--
########################################
@ FileName:test.xml
@ Date:2014-02-20  10:34:24
@ Editor:Garnett
@ Version:1.0.1
@ Log:这是第二个注释
########################################
-->
<student>
    <name>张三</name>
    <age>23</age>
    <address>北京</address>
</student>

请问该怎么实现呢?
------解决方案--------------------

Node common=doc.createComment("注释内容");
doc.appendChild(common);

------解决方案--------------------
引用:
Quote: 引用:


Node common=doc.createComment("注释内容");
doc.appendChild(common);

那如果我需要提取这两个注释内容,用正则表达式该怎么做呢?即要得到字符串:
<!--
########################################
@ FileName:test.xml
@ Date:2014-02-20  10:24:24
@ Editor:Kobe
@ Version:1.0.0
@ Log:这是一个测试文件
########################################
-->
<!--
########################################
@ FileName:test.xml
@ Date:2014-02-20  10:34:24
@ Editor:Garnett
@ Version:1.0.1
@ Log:这是第二个注释
########################################
-->

Pattern pattern= Pattern.compile("<!--([\\s\\S]*)-->");
     Matcher m=pattern.matcher(xmlString);
     if(m.find()){
     log=xmlString.substring(m.start(), m.end());
     }else{
     log=null;
     }