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();
Related
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 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 am trying to implement some functions that will convert one object to another with XslCompiledTransform.
I found some implementations for Serializing an object to XML string and DeSerialize the XML string to an object.
Another function does the XslCompiledTransform from object1 to obejbct2.
To generate the XSLT file i used the Altova MapForce, just loaded the XML of the serialized objects and mapped some attributes.
Now for the problems:
first I noticed that the XslCompiledTransform doesn't work with XSLT version 2.0. is there any newer functions that do work with XSLT 2.0? maybe some settings?
secondly I get an exception when trying to DeSerialize the XML to an object:
"There was an error deserializing the object of type myObject Input string was not in a correct format."
I don't understand where is the problem.
Does anybody have a sample code that does such a thing? all I find in google are Transformations of HTML code and not objects.
Here are the functions:
private static string runXSLT(string xsltFile, string inputXML)
{
XmlDocument XmlDoc = new XmlDocument();
// Load the style sheet.
XslCompiledTransform xslt = new XslCompiledTransform(true);
xslt.Load(xsltFile);
StringReader StrReader = new StringReader(inputXML);
XmlTextReader XmlReader = new XmlTextReader(StrReader);
//Create an XmlTextWriter which outputs to memory stream
Stream stream = new MemoryStream();
XmlWriter writer = new XmlTextWriter(stream, Encoding.UTF8);
// Execute the transform and output the results to a file.
xslt.Transform(XmlReader, writer);
stream.Position = 0;
XmlDoc.Load(stream);
return XmlDoc.InnerXml;
}
public static string SerializeAnObject(object AnObject)
{
XmlDocument XmlDoc = new XmlDocument();
DataContractSerializer xmlDataContractSerializer = new DataContractSerializer(AnObject.GetType());
MemoryStream MemStream = new MemoryStream();
try
{
xmlDataContractSerializer.WriteObject(MemStream, AnObject);
MemStream.Position = 0;
XmlDoc.Load(MemStream);
return XmlDoc.InnerXml;
}
finally
{
MemStream.Close();
}
}
public static Object DeSerializeAnObject(string XmlOfAnObject, Type ObjectType)
{
StringReader StrReader = new StringReader(XmlOfAnObject);
DataContractSerializer xmlDataContractSerializer = new DataContractSerializer(ObjectType);
XmlTextReader XmlReader = new XmlTextReader(StrReader);
try
{
Object AnObject = xmlDataContractSerializer.ReadObject(XmlReader);
return AnObject;
}
finally
{
XmlReader.Close();
StrReader.Close();
}
}
Thanks allot,
Omri.
XslCompiledTransform does not support XSLT 2.0. In fact, XSLT 2.0 is not supported within the .NET Framework at all (you could try the Saxon version for .NET, but be aware that this is just the Java version running inside IKVM).
From your description I did not understand why you are taking the detour via XML to convert one object into another. Why don't you simply provide a constructor in your target object that takes your input object as a paramater? Then you can code all the mapping inside that constructor. This is not onlyby far more efficient than serializing, transforming and deserializing your objects you will also get the type safety of C#.
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());
}
}
}