问题
I am having an issue with an XML response and formatting it into CSV which can then later be opened as an XLS and see the entire response into a single cell. I know.. its not how I would do it either, but they get what they ask for.
So far I have tried to use a string builder. This has been successful in formatting the response into a single line string, I have tested this by writing it to a text file and copying it to Eclipse.. when I place single quotes around the XML it turns to a string.
When trying to take this same response in its single line format and stick it into a csv file.. the csv file is breaking on comma's in the XML string and placing the response across several dozen cells.
BufferedReader br = new BufferedReader(new FileReader(new File('responseXml.txt')));
String l;
StringBuilder sb = new StringBuilder();
while((l=br.readLine())!= null){sb.append(l.trim());
File respfile = new File("outresp.txt")
respfile.append(l)
println respfile.text
//verified single line string
respContents = new File("outresp.txt").text
}
File file = new File('outXML.csv')
file.append(respContents)
println file.text
// open csv still broke across many lines
What I would like is a single xml string into a single xls cell.
回答1:
to fit value into single column in csv (excel) you have two choices:
- remove all new lines (
\r\n
) and comas (,
) - replace each doublequote (
"
) with two ones (""
) and wrap whole value with doublequotes.
the second variant allows you to keep the original (multiline) string format in one excel cell.
here is the code for second variant:
//assume you have whole xml in responseXml variable
def responseXml = '''<?xml version="1.0"?>
<aaa text="hey, you">
<hello name="world"/>
</aaa>
'''
//take xml string in double quotes and escape all doublequotes
responseXml = '"'+ responseXml.replaceAll(/"/,'""') + '"'
def csv = new File('/11/1.csv')
csv.setText("col1,col2,xml\nfoo,bar") // emulate some existing file
csv.append(",${responseXml}\n")
as a result:
来源:https://stackoverflow.com/questions/58280694/using-string-builder-to-place-xml-in-single-csv-xls-column-not-working