I have code for read xml:
string xmlread = new StreamReader(response.GetResponseStream()).ReadToEnd();
Custom custom = new Custom();
TextReader txtReader = new StreamReader(Convert.ToString(xmlread));
XmlSerializer xmlSerializer = new XmlSerializer(typeof(custom));
custom = (Custom)xmlSerializer.Deserialize(txtReader);
but xml has the form
<?xml version=\"1.0\"?>\n<instacheat>\n <hash>5d02c2151c9d147b2219b371b7d383b3665e</hash>\n</instacheat>\n\r\n
and because gives me an error "It contains invalid characters."
Try getting the stream reader to detect the text encoding:
string xmlread = new StreamReader(response.GetResponseStream(), true).ReadToEnd();
To get rid of \r\n, I suggest using a regex as a quick solution
xmlread = System.Text.RegularExpressions.Regex.Replace(xmlread, #"\\r|\\n", "")
Related
Hello all I have the following XML string generated from file. I want to deserialize it.
<CustomerName>TEST</CustomerName>
<PONumber></PONumber>
<ProcessedBy>Jerry Cooke</ProcessedBy>
<ProcessDate>03-05-2004 14:00:49</ProcessDate>
<TagNumber></TagNumber>
<SerialNumber>134</SerialNumber>
I am using the following code.
string Data = upperxmlstring
XmlTextReader reader = new XmlTextReader(Data);
obj = (T)serializer.Deserialize(reader);
reader.Close();
I am getting following exception "Illegal characters in path." This error comes at XmlTextReader reader = new XmlTextReader(Data);
Please help me in solving it.
new XmlTextReader(string) expects a filename, not the content. To read the content from a string you'll have to instantiate a TextReader for that string. Use StringReader for that.
Better still, don't use XmlTextReader, since it's been deprecated. Use XmlReader.Create instead:
string Data = upperxmlstring;
XmlReader reader = XmlReader.Create(new StringReader(Data));
obj = (T)serializer.Deserialize(reader);
reader.Close();
I've a class correctly defined and after serialize it to XML I'm getting no encoding.
How can I define encoding "ISO-8859-1"?
Here's a sample code
var xml = new XmlSerializer(typeof(Transacao));
var file = new FileStream(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "transacao.xml"),FileMode.OpenOrCreate);
xml.Serialize(file, transacao);
file.Close();
Here are the beginning of xml generated
<?xml version="1.0"?>
<requisicao-transacao xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<dados-ec>
<numero>1048664497</numero>
The following should work:
var xml = new XmlSerializer(typeof(Transacao));
var fname = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "transacao.xml");
var appendMode = false;
var encoding = Encoding.GetEncoding("ISO-8859-1");
using(StreamWriter sw = new StreamWriter(fname, appendMode, encoding))
{
xml.Serialize(sw, transacao);
}
If you don't mind me asking, why do you need ISO-8859-1 encoding in particular? You could probably use UTF-8 or UTF-16 (they're more commonly recognizable) and get away with it.
Create a StreamWriter with the desired encoding:
System.Text.Encoding code = *WhateverYouWant*
StreamWriter sw = new StreamWriter(file, code);
I want load xml documents, but there are special symbols like : ąčęėįšųū and i get error Invalid character in the given encoding. Question is how to encode this characters before load xml ?
// load xml result from Google weather
XDocument xd = XDocument.Load("http://www.google.com/ig/api?weather=vilnius&hl=ru");
I would give this a try
WebClient cln = new WebClient();
var str = cln.DownloadString("http://www.google.com/ig/api?weather=vilnius&hl=ru");
XDocument xDoc = XDocument.Load(new StringReader(str));
using (StreamReader sr = new StreamReader("http://www.google.com/ig/api?weather=vilnius&hl=ru", true))
{
XDocument xdoc = XDocument.Load(sr);
}
The problem is with the encoding. If you use a StreamReader it should detect what encoding the response is in and then allow you to call XDocument.Load.
I have an XML file that I deserialize, the funny part is the XML file is the was serialized
using the following code:
enter code here
var serializer = new XmlSerializer(typeof(CommonMessage));
var writer = new StreamWriter("OutPut.txt");
serializer.Serialize(writer, commonMessage);
writer.Close();
And i m trying to deserialized it again to check if the output match the input.
anyhow here is my code to deserialize:
var serializer = new XmlSerializer(typeof(CommonMessage));
var reader = new StringReader(InputFileName);
CommonMessage commonMessage = (CommonMessage)serializer.Deserialize(reader);
Replace StringReader with StreamReader and it will work fine. StringReader reads value from the string (which is file name in your case).
I just had the same error message but different error source. In case someone has the same problem like me. I chopped off the very first char of my xml string by splitting strings. And the xml string got corrupted:
"?xml version="1.0" encoding="utf-16"?> ..." // my error
"<?xml version="1.0" encoding="utf-16"?> ..." // correct
(1,1) means basically first char of the first line is incorrect and the string can't be deserialized.
include in your CommonMessage class the XmlRoot element tag with your xmlroot eg:[XmlRoot("UIIVerificationResponse")]
You should disable the order mark in the StreamWriter constructor like this:
UTF8Encoding(false)
Full sample:
using (MemoryStream stream = new MemoryStream())
using (StreamWriter writer = new StreamWriter(stream, new UTF8Encoding(false)))
{
xmlSerializer.Serialize(writer, objectToSerialize, ns);
return Encoding.UTF8.GetString(stream.ToArray());
}
I'm getting an "Illegal characters in path error" while using XMLTextReader method. Basically, I'm sending a long URL to tr.im, and tr.im sends the response as an XML stream, which I'm trying to parse but I get the above mentioned error. Can you guys guide me as to why I'm getting this error and where I'm going wrong? Here's the code:
WebRequest wrURL;
Stream objStream;
string strURL;
wrURL = WebRequest.Create("http://api.tr.im/api/trim_url.xml?url=" + HttpUtility.UrlEncode(txtURL.Text));
objStream = wrURL.GetResponse().GetResponseStream();
StreamReader objSReader = new StreamReader(objStream);
strURL = objSReader.ReadToEnd().ToString();
XmlTextReader reader = new XmlTextReader(strURL); //getting the error at this point
I'm using Visual Studio 2008, Express Edition
The reason why is you are using the constructor of XmlTextReader which takes a file path as the parameter but you're passing XML content instead.
Try the following code
XmlTextReader reader = new XmlTextReader(new StringReader(strURL));
XmlTextReader constructor accepts a string that points to the URL where an XML file is stored. You are passing it the XML itself which of course is an invalid path. Try this instead:
using (var client = new WebClient())
{
var xml = client.DownloadString("http://api.tr.im/api/trim_url.xml?url=" + HttpUtility.UrlEncode(txtURL.Text));
using (var strReader = new StringReader(xml))
using (var reader = XmlReader.Create(strReader))
{
}
}
The XmlTextReader(string) constructor expects a file path, not the actual XML data.
You can create an XML reader directly from the stream. The recommended way to do this is using the XmlReader.Create method:
XmlReader reader = XmlReader.Create(objStream);
You should print or otherwise display strUrl. Once you can actually see the path that you're passing to the test reader, it should be obvious what the path error is.
Also, just looking at the code, it seems like the response itself might be XML, in which case you should pass objSReader directly to the XmlTextReader constructor.
private void csv2_Load(object sender, EventArgs e)
{
DataSet ds = new DataSet();
DataSet dsSchema = new DataSet();
dsSchema.ReadXml(#"C:\Working\Teradata\ssis\Sample.xml");
StringReader sreader = new StringReader(ToXml(dsSchema));
ds.ReadXmlSchema(sreader);
ds.ReadXml(#"C:\Working\Teradata\ssis\Sample.xml");
ExportTableToCsvString(ds.Tables["session"], true, #"C:\Working\Teradata\ssis\op\session.csv");
BuildDynamicTable(ds, #"C:\Working\Teradata\ssis\op\");
}
public string ToXml(DataSet ds)
{
using (var memoryStream = new MemoryStream())
{
using
(
TextWriter streamWriter = new StreamWriter(memoryStream))
{
var xmlSerializer = new XmlSerializer(typeof(DataSet));
xmlSerializer.Serialize(streamWriter, ds);
return Encoding.UTF8.GetString(memoryStream.ToArray());
}
}
}