使用XMLStreamWriter编写非转义属性

时间:2014-10-21 14:02:36

标签: java xml dtd stax

我正在尝试将自定义实体编写为属性值:

out.writeAttribute("storeent_id", "&MAR_STOREENT_ID;");

所需:

<dmactivity
  dmactivity_id="@dmactivity_id_collateral_21003"
  storeent_id="&MAR_STOREENT_ID;"
  optcounter="0"
/>

实际

<dmactivity
    dmactivity_id="@dmactivity_BoysPantsRow2_Content"
    storeent_id="&amp;MAR_STOREENT_ID;"
    optcounter="0"
/>

1 个答案:

答案 0 :(得分:0)

制作自定义Writer,将MYENTITY_MAR_STOREENT_ID:替换为&MAR_STOREENT_ID;。适合小xmls。

public class ReplacingWriter extends StringWriter {

    protected Writer out;

    public ReplacingWriter(Writer out) {
        this.out = out;
    }

    @Override
    public void close() throws IOException {
        String s = toString();
        for (int i = 0, len = rules.size(); i < len;) {
            String a = rules.get(i++);
            String b = rules.get(i++);
            s = s.replaceAll(a, b);
        }
        out.write(s);
        out.close();
    }

    private final ArrayList<String> rules = new ArrayList<String>();

    public void addRule(String regex, String replacement) {
        rules.ensureCapacity(rules.size() + 2);
        rules.add(regex);
        rules.add(replacement);
    }
}
...
Serializer ser = processor.newSerializer();
rwr = new ReplacingWriter(fos);
rwr.addRule("MYENTITY_([^:]*):", "&$1;");
ser.setOutputWriter(rwr);
...
Serializer ser = processor.newSerializer();
rwr = new ReplacingWriter(fos);
rwr.addRule("MYENTITY_([^:]*):", "&$1;");
ser.setOutputWriter(rwr);
...
out.writeAttribute("storeent_id", "MYENTITY_MAR_STOREENT_ID:");