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());
}
}
}
Related
What I want to accomplish is reading an xml file from a website (http://xml.buienradar.nl/). I have been reading about what to use, but I can't see the forest for the trees! Should I be using WebRequest, or XmlDocument, or XDocument, or XmlReader, or XmlTextReader, or? I read that XmlDocument and XDocument read the whole file into memory, and XmlReader doesn't. But is that a problem in this case? What if indeed the xml file is huge?
Can someone help me find a way?
Thanks!
To read huge XML without loading all of it into memory, you can use XmlReader class. But please note that this method requires more code than XDocument or even XmlDocument solution.
var h = WebRequest.CreateHttp("http://xml.buienradar.nl/");
using (var r = h.GetResponse())
using (var resp = r.GetResponseStream())
using (var sr = new StreamReader(resp))
using (var xr = new XmlTextReader(sr))
{
while (xr.Read())
{
// doing something with xr
// for example print it's current node value
Console.WriteLine(xr.Value);
}
}
If you want to test for large XML file, you can try XML from http://www.ins.cwi.nl/projects/xmark/Assets/standard.gz.
It is over 30 MB gzipped. With this method, XML processing don't require much memory, it even don't wait for whole file to finished downloading.
Test code:
var h = WebRequest.CreateHttp("http://www.ins.cwi.nl/projects/xmark/Assets/standard.gz");
using (var r = h.GetResponse())
using (var resp = r.GetResponseStream())
using (var decompressed = new GZipStream(resp, CompressionMode.Decompress))
using (var sr = new StreamReader(decompressed))
using (var xr = new XmlTextReader(sr))
{
while (xr.Read())
{
// doing something with xr
// for example print it's current node value
Console.WriteLine(xr.Value);
}
}
XmlTextReader provides a faster mechanism for reading xml.
string url="http://xml.buienradar.nl/";
XmlTextReader xml=new XmlTextReader(url);
while(xml.Read())
{
Console.WriteLine(xml.Value);
}
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 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", "")
I didn't know that I can use XSD schema to serialize received XML file. I used xsd.exe to generate cs class from XSD file and now I need to use that class to get data in class properties but I miss one thing and I need help.
This is the code:
private void ParseDataFromXmlDocument_UsingSerializerClass(XmlDocument doc)
{
XmlSerializer ser = new XmlSerializer(typeof(ClassFromXsd));
string filename = Path.Combine("C:\\myxmls\\test", "xmlname.xml");
ClassFromXsdmyClass = ser.Deserialize(new FileStream(filename, FileMode.Open)) as ClassFromXsd;
if (myClass != null)
{
// to do
}
...
Here I use XML file from drive. And I want to use this XmlDocument from parameter that I passed in. So how to adapt this code to use doc instead XML from drive?
You could write the XmlDocument to a MemoryStream, and then Deserialize it like you already did.
XmlDocument doc = new XmlDocument();
ClassFromXsd obj = null;
using (var s = new MemoryStream())
{
doc.Save(s);
var ser = new XmlSerializer(typeof (ClassFromXsd));
s.Seek(0, SeekOrigin.Begin);
obj = (ClassFromXsd)ser.Deserialize(s);
}
I simply want to add a line to an SPFile object, which is a simple txt file.
Is there a simple way to do this ? I was thinking
Thanks
EDIT : that's what i have for the moment :
public static void addLine(SPFile file, string line)
{
using(System.IO.StreamWriter strWriter = new System.IO.StreamWriter(file.OpenBinaryStream())){
strWriter.WriteLine(line);
}
}
I don't have any error here, but the file doesn't get saved. I've tried to do something like :
file.SaveBinary( args )
But i don't know what to put in args.
If you can help me.
Thanks
You need SPFile.OpenBinaryStream, one of SPFile.SaveBinary to read/write. Some string manipulation of TextReader created over resulting stream like TextReader.ReadToEnd and write resulting data to MemoryStream with TextWriter.
Warning: non-compiled code below:
using (var readStream = file.OpenBinaryStream())
{
using(var reader = new StreamReader(readStream)
{
var allText = reader.ReadToEnd();
var writeStream = new MemoryStream();
using(var writer = new TextWriter(writeStream))
{
writer.Write(allText);
writer.Write(extraText);
}
file.SaveBinary(writeStream.ToArray();
}
}