【问题标题】:How to add CDATA in a XML without the Loss of <br/> tag in java?java - 如何在没有丢失<br/>标签的情况下在XML中添加CDATA?
【发布时间】:2015-08-12 08:56:03
【问题描述】:

如何在Java中不丢失&lt;br/&gt;标签的情况下在XML中添加CDATA?

我需要将Cdata添加到Stringtemp1中,还需要保留break标签。

然后是下面的程序和示例:

i) 程序-AddCDATASectionToDOMDocument.java

ii) 输入 xml

iii) 所需输出

i) 程序-AddCDATASectionToDOMDocument.java

public class AddCDATASectionToDOMDocument {

    public static void main(String[] args) throws Exception {
        xmlreader xmlr = new xmlreader();
        String temp1 = xmlr.xmlFileReader("example.xml", "contentmeta","subtitle");
        String temp2 = "<![CDATA[" + temp1 + "]]>";
        xmlr.xmlFileWriter("example.xml", "contentmeta", "subtitle", temp2);
    }

}

ii)example.xml

iii) 要求输出

【问题讨论】:

    标签: java xml cdata


    【解决方案1】:

    使用正则表达式而不是用 DOM 解析它怎么样?此代码可能适用于您的示例:

        String input = new String(Files.readAllBytes(Paths.get("file1.xml")));
        final Pattern regex = Pattern.compile("<subtitle>(.+?)</subtitle>");
        final Matcher matcher = regex.matcher(input);
        String modification;
        if (matcher.find()) {
             modification = "<subtitle><![CDATA["+matcher.group(1)+"]]></subtitle>";
             String output = matcher.replaceFirst(modification);
             System.out.println(output);
             FileOutputStream outputStream = new FileOutputStream("file2.xml");
             outputStream.write(output.getBytes());
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多