how do i read xml file value - flutter

this is my XML data file:
<?xml version = "1.0"?>
<contact-info>
<name>Tanmay Patil</name>
<company>TutorialsPoint</company>
<phone>(011) 123-4567</phone>
</contact-info>
and this is my flutter code:
Future _xml() async {
http.Response response = await http.get(Uri.parse(url));
XmlData = XmlDocument.parse(response.body);
final wantData = XmlData!.findAllElements('contact-info');
}
please how i can get the value TutorialsPoint from my xml file

Use the xml package
import 'package:xml/xml.dart' as xml;
var xmldata='<?xml version = "1.0"?>
<contact-info>
<name>Tanmay Patil</name>
<company>TutorialsPoint</company>
<phone>(011) 123-4567</phone>
</contact-info>';
void main() {
var contact = xml.parse(xmldata);
print(contact.findAllElements('phone'));
}

Related

how to convert json string in dart flutter?

I have string response like this, I got only below response of my api.
{authToken: msadnmsandnasdn}
and I have to convert as below.
{"authToken": "msadnmsandnasdn"}
So how i can do this please Help me.
You can use various manipulation operations to do that manually:
import 'dart:convert';
void main() {
var s = "{authToken: msadnmsandnasdn, name:risheek}";
var kv = s.substring(0,s.length-1).substring(1).split(",");
final Map<String, String> pairs = {};
for (int i=0; i < kv.length;i++){
var thisKV = kv[i].split(":");
pairs[thisKV[0]] =thisKV[1].trim();
}
var encoded = json.encode(pairs);
print(encoded);
}
Output:
{"authToken":"msadnmsandnasdn"," name":"risheek"}
You need to use jsonDecode on that string like this:
var response = {authToken: msadnmsandnasdn....};
var result = jsonDecode(response);

Dart is replacing "&" with "\u0026" in a URL

I am using flutter to process a link and download it to the device using dio package.
But the problem is dart is replacing all '&' with '\u0026' and making the link unusable. is there a way to avoid this problem? Thanks in advance.
Here's the code:
const uuid = Uuid();
final Dio dio = Dio();
// * create random id for naming downloaded file
final String randid = uuid.v4();
// * create a local instance of state all media
List<MediaModel> allMedia = state.allMedia;
// * create an instance of IGDownloader utility class from ~/lib/utilities
final IGDownloader igd = IGDownloader();
// * make a download link from provided link from the GetNewMedia event
final link = await igd.getPost(event.link);
link.replaceAll('\u0026', '&');
print(await link);
Output:
// expected : "http://www.example.com/example&examples/"
// result: "http://www.example.com/example\u0026example"
Pass your url to cleanContent function and don't forget to add imports
import 'package:html/parser.dart';
import 'package:html_unescape/html_unescape.dart';
static String cleanContent(String content, {bool decodeComponent = false}) {
if (content.contains("<p>")) {
content = content.replaceAll("<p>", "").trim();
}
if (content.contains("</p>")) {
content = content.replaceAll("</p>", "").trim();
}
var unescape = HtmlUnescape();
content = unescape.convert(content).toString();
if (content.contains("\\<.*?\\>")) {
content = content.replaceAll("\\<.*?\\>", "").trim();
}
content = parseHtmlString(content,decodeComponent: decodeComponent);
return content;
}
static String parseHtmlString(String htmlString,{bool decodeComponent = false}) {
final document = parse(htmlString);
String parsedString = parse(document.body!.text).documentElement!.text;
if(parsedString.contains("%3A")){
parsedString = parsedString.replaceAll("%3A", ":");
}
if(parsedString.contains("%2F")){
parsedString = parsedString.replaceAll("%2F", "/");
}
if(decodeComponent){
parsedString = Uri.decodeComponent(parsedString);
}
return parsedString;
}
replaceAll returns the modified string, but leaves original String untouched.
Try:
print(await link.replaceAll('\u0026', '&'));
or
newLink = link.replaceAll('\u0026', '&');
print(await newLink);

How to solve Error: XMLHttpRequest error. in Flutter Web

I want to use to Google places api and
I am trying to call this api but I am getting this. error
Error: XMLHttpRequest error.
static Future<List<Result>?> searchPlaces(context, String query) async {
String mapApiKey = "API_KEY";
String _host = 'https://maps.googleapis.com/maps/api/place/textsearch/json';
final url = '$_host?query=$query&key=$mapApiKey';
//
var response = await http.get(Uri.parse(url));
print(response.body);
//
if (response.statusCode == '200') {
GPlacesSearch result = GPlacesSearch.fromJson(jsonDecode(response.body));
return result.results!;
} else
return null;
}
}
I don't know which platform you are using, but I guess the solution would be to disable chrome web security.
If you are working on mac try the following steps
Go to flutter\bin\cache and remove a file named: flutter_tools.stamp
Go to flutter\packages\flutter_tools\lib\src\web and open the file chrome.dart.
Find '--disable-extensions'
Add '--disable-web-security'
And if you are working on windows just search for how to disable web security for chrome
Use this url 'https://cors-anywhere.herokuapp.com' before your actual url e.g.
String baseUrl = 'https://cors-anywhere.herokuapp.com';
String actualUrl = 'https://maps.googleapis.com/maps/api/place/textsearch/json';
String finalUrl = "$baseUrl/$actualUrl";
static Future<List<Result>?> searchPlaces(context, String query) async {
String mapApiKey = "YOUR_KEY_HERE";
var _sessionToken = Uuid().v4();
String _host =
'https://cors-anywhere.herokuapp.com/https://maps.googleapis.com/maps/api/place/textsearch/json';
final url = '$_host?query=$query&key=$mapApiKey';
//
var response = await http.get(Uri.parse(url);
//
GPlacesSearch result = GPlacesSearch.fromJson(jsonDecode(response.body));
return result.results!;
}
}

can't fetching json in flutter

It Work When String is used BUT Can't fetch String Object.
it Works :-
String? url = "https://api.thedogapi.com/v1/images/search";
var raw = await http.get(Uri.parse(url));
it is Not working :-
getInfoFromSharedPref() async {
dogApiLink = await SharedPreferenceHelper().getDogName();
}
var raw = await http.get(Uri.parse('${dogApiLink}'));
where dogApiLink is String and having Link But Not working.
bro it's direct .. I just don't understand if the return from the shared preferences that you are taking is a link ???? if it's only dog name then that's your problem.. if it's a legitimate link then
{
String uri = "The link";
var response = await http.get(Uri.parse(uri), "The headers of the api").then(){
// The task you wanna perform.
}
}

Download mp3 file at browser through API .net core

Was trying to download an mp3 file in a browser through the API that I created. But instead of receiving an mp3 file. I keep getting JSON format response. I had referred from answer in return-file-in-asp-net-core-web-api, but still, I can't download the mp3 file.
Is there any mistake that I've overlooked, please kindly help?
This is my downloading method from UI
void DownloadRecording(RecordingHistory voicehistory)
{
try
{
using (var client = new WebClient())
{
client.DownloadFile("https://2d489fd863a2.ngrok.io/api/download/" + voicehistory.RecordingId + ".mp3", voicehistory.RecordingId + ".mp3");
}
}
catch { }
}
This is my api function for downloading mp3 from server
[HttpGet("download/{recordingFile}")]
public async Task<IActionResult> DownloadVoiceRecording(string recordingFile)
{
string filePath = Directory.GetCurrentDirectory() + #"\audio\Processed\" + recordingFile;
var memory = new MemoryStream();
using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
{
await stream.CopyToAsync(memory);
}
memory.Position = 0;
var types = GetMimeTypes();
var ext = Path.GetExtension(filePath).ToLowerInvariant();
return File(filePath, types[ext], recordingFile);
}
private Dictionary<string, string> GetMimeTypes()
{
return new Dictionary<string, string>
{
{".mp3", "audio/mpeg"},
{".wav","audio/wav" }
};
}
This is the response I get from browser and Postman
{
"Version": "2.0.0.0",
"StatusCode": 200,
"Message": "Status 200 OK",
"Result":"��#� ... ... /// A lot of random symbol here
}
Because the first parameter of the return value File is a type of Stream, memory needs to be passed in.
[HttpGet("download/{recordingFile}")]
public async Task<IActionResult> DownloadVoiceRecording(string recordingFile)
{
string filePath = Directory.GetCurrentDirectory() + #"\audio\Processed\" + recordingFile;
var memory = new MemoryStream();
using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
{
await stream.CopyToAsync(memory);
}
memory.Position = 0;
var types = GetMimeTypes();
var ext = Path.GetExtension(filePath).ToLowerInvariant();
return File(memory, types[ext], recordingFile);
}
I'm using Blazor for this. It turns out that there was an API response wrapper in Blazor APIReponse middleware. I had to put my API into an exception so it won't turn into JSON when I access it. It works finally.
Below is the APIReponse wrapper in Blazor.
var formattedRequest = await FormatRequest(request);
var originalBodyStream = httpContext.Response.Body;
using (var responseBody = new MemoryStream())
{
try
{
string responseBodyContent = null;
var response = httpContext.Response;
if (new string[] { "/api/localization", "/api/data", "/api/externalauth", "/api/download" }.Any(e => request.Path.StartsWithSegments(new PathString(e.ToLower()))))
await _next.Invoke(httpContext);
else
{
response.Body = responseBody;
await _next.Invoke(httpContext);
//wrap response in ApiResponse
if (httpContext.Response.StatusCode == Status200OK)
{
responseBodyContent = await FormatResponse(response);
await HandleSuccessRequestAsync(httpContext, responseBodyContent, Status200OK);
}
else
await HandleNotSuccessRequestAsync(httpContext, httpContext.Response.StatusCode);
}