Correct xml escaping in Java -
i need convert csv xml , outputstream. rule convert "
"
in code.
input csv row:
{"test":"value"}
expected output:
<root> <child>{"test":"value"}</child> <root>
current output:
<root> <child>{&quot;test&quot;:&quot;value&quot;}</child> <root>
code:
file file = new file(filepath); bufferedreader reader = null; documentbuilderfactory domfactory = documentbuilderfactory.newinstance(); documentbuilder dombuilder = domfactory.newdocumentbuilder(); document newdoc = dombuilder.newdocument(); element rootelement = newdoc.createelement("root"); newdoc.appendchild(rootelement); reader = new bufferedreader(new filereader(file)); string text = null; while ((text = reader.readline()) != null) { element rowelement = newdoc.createelement("child"); rootelement.appendchild(rowelement); text = stringescapeutils.escapexml(text); rowelement.settextcontent(text); } bytearrayoutputstream outputstream = new bytearrayoutputstream(); source xmlsource = new domsource(newdoc); result outputtarget = new streamresult(outputstream); transformerfactory.newinstance().newtransformer().transform(xmlsource, outputtarget); system.out.println(new string(baos.tobytearray()))
could please help? miss , when &
convert &
?
the xml library automatically escape strings need xml-escaped, don't need manually escape using stringescapeutils.escapexml
. remove line , should exactly you're looking for properly-escaped xml.
xml doesn't require "
characters escaped everywhere, within attribute values. valid xml already:
<root> <child>{"test":"value"}</child> <root>
you escape quotes if had attribute contained quote, such as: <child attr="properly "ed"/>
this 1 of main reasons use xml library: subtleties of quoting handled you. no need read xml spec make sure got quoting rules correct.
Comments
Post a Comment