I want to write xml string to XML file. I am using http service to read xml string. After reading xml string from service I convert this string to formatted string and then write it to XML file. The issue is that the formatted string is not showing XML layout properly. It is showing the closing and end tag in the format I highlighted in the screenshot below:
Here is the screenshot of server response and I also printed the formatted form of that XML string.
Here is the code snippet.
Future readLayoutFile() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
String token = prefs.getString('token');
print('token:$token');
Response response;
Dio dio = new Dio();
dio.interceptors
.add(InterceptorsWrapper(onRequest: (RequestOptions options) async {
var customHeaders = {
'authorization': token,
// other headers
};
options.headers.addAll(customHeaders);
return options;
}));
try {
response = await dio.post(globals.ursl.getURL(URLS.READLAYOUTURL));
print('XML STRING FROM HTTP SERVICE:');
print('${response}');
if (response.statusCode == 200) {
Map<String, dynamic> mapobject = response.data;
var success = mapobject['success'];
if (success == 1) {
XmlDocument xmlDocument = XmlDocument.fromString(
mapobject['Layout']['xml_Save'],
trimWhitespace: true,
parseCdataAsText: true,
parseCharacterEntities: true,
);
print('FORMATTED XML STRING :${xmlDocument.toFormattedString()}');
xmlFile.writeAsStringSync(xmlDocument.toFormattedString());
await parseXmlData(xmlFile.readAsStringSync());
} else {
print(response);
}
} else {
print('response code not 200');
print(response);
}
} catch (error) {
print('ERROR IN READING $error');
}
}
Anyone please help me how to solve this issue.
Thanks in advance.
CodePudding user response:
WAI. As per documentation:
By default, only the &, <, and > characters will be encoded.
Check out the .toString(encodeCharacterEntities: false)
method.
UPD:
Also as per the same documentation,
toFormattedString is rather rudimentary at the moment and I'd like to add additional formatting options to it at some point).
Try another library, for example this one. Here is an example for you of how your string can be parsed and prettified:
import 'package:xml/xml.dart';
void main(List<String> arguments) {
String xmlString1 =
'''<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\" ?>\n<terminal>\n\t<favItems>\n\t</favItems>\n\t<regularItems>\n\t\t<menu>\n\t\t\t<menuId>\n\t\t\t\t1\n\t\t\t</menuId>\n\t\t\t<name>\n\t\t\t\tLUNCH\n\t\t\t</name>\n\t\t</menu>\n\t\t<menu>\n\t\t\t<menuId>\n\t\t\t\t2\n\t\t\t</menuId>\n\t\t\t<name>\n\t\t\t\tBREAKFAST\n\t\t\t</name>\n\t\t</menu>\n\t</regularItems>\n</terminal>\n''';
XmlDocument d = XmlDocument.parse(xmlString1);
print(d.toXmlString(pretty: true));
}
Result here.