My code is as follows.
using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream("TestStore1.xml", FileMode.Open, isoStore))
{
using (StreamReader reader = new StreamReader(isoStream))
{
str = reader.ReadToEnd();
XmlDocument doc = new XmlDocument();
doc.LoadXml(str);
string json = JsonConvert.SerializeXmlNode(doc);
}
}
It is giving the error at the line of string json = JsonConvert.SerializeXmlNode(doc);
Error - Newtonsoft.Json.JsonConvert' does not contain a definition for 'SerializeXmlNode'
If you are using dotnet core, install the Newtonsoft.Json package via nuget.
Related
In public ScenarioPage() of ScenarioPage.cs I have the following code to read from a json file:
var assembly = typeof(ScenarioPage).GetTypeInfo().Assembly;
Stream stream = assembly.GetManifestResourceStream("firstSession.json");
using (StreamReader reader = new StreamReader(stream)) // System.ArgumentNullException
{
var json = reader.ReadToEnd();
List<SessionModel> data = JsonConvert.DeserializeObject<List<SessionModel>>(json);
foreach(SessionModel scenario in data)
{
label.Text = scenario.title;
break;
};
}
I am getting an ArgumentNullException for the stream input. firstSession.json is in the same folder as ScenarioPage.cs, and it is set as an embedded resource. It seems like Visual Studio is not recognizing that my json file is there. Is this is a bug? Or is there something wrong with my code?
Where did you put the Json File, I put it in the Json File in the root Of PCL like following screenshot.
Then use following code to read the Json File.
void GetJsonData()
{
string jsonFileName = "firstSession.json";
ContactList ObjContactList = new ContactList();
var assembly = typeof(MainPage).GetTypeInfo().Assembly;
Stream stream = assembly.GetManifestResourceStream($"{assembly.GetName().Name}.{jsonFileName}");
using (var reader = new System.IO.StreamReader(stream))
{
var jsonString = reader.ReadToEnd();
//Converting JSON Array Objects into generic list
ObjContactList = JsonConvert.DeserializeObject<ContactList>(jsonString);
}
EmployeeView.ItemsSource = ObjContactList.contacts;
}
And here is running GIF.
I update my demo to you. you can test it
https://github.com/851265601/Xamarin.Android_ListviewSelect/blob/master/PlayMusicInBack.zip
I am converting xml to html using xslt 3.0 saxon-HE 9.8 library. Using it in c# code.
I am passing xml and xslt file path in input to get it transformed and get output.
Can anyone please let me know how can I pass xml as string and xslt as string as input in c# code for processing it.
Below is my code.
public static string Transform_XML(string param, string inputfile, string xsltfilename)
{
var xslt = new FileInfo(xsltfilename);
var input = new FileInfo(inputfile);
// Compile stylesheet
var processor = new Processor();
var compiler = processor.NewXsltCompiler();
var executable = compiler.Compile(new Uri(xslt.FullName));
XPathDocument doc = new XPathDocument(new StringReader(param));
DocumentBuilder db = processor.NewDocumentBuilder();
XdmNode xml;
using (XmlReader xr = XmlReader.Create(new StringReader(param)))
{
xml = db.Build(xr);
}
// Do transformation to a destination
var destination = new DomDestination();
using (var inputStream = input.OpenRead())
{
var transformer = executable.Load();
transformer.SetParameter(new QName("", "", "user_entry"), xml);
transformer.SetInputStream(inputStream, new Uri(input.DirectoryName));
transformer.Run(destination);
}
return destination.XmlDocument.InnerXml.ToString();
}
Want to pass xml and xslt as string instead of file path.
UPDATE 1
Got the solution for passing xml and xsl as string in c#. Below is the updated code.
private string Transform_XML(string param, string param_name, string inputfile, string xsltfilename)
{
string xslt_input = System.IO.File.ReadAllText(xsltfilename + ".xslt");
string xml_input = System.IO.File.ReadAllText(inputfile + ".xml");
// Compile stylesheet
var processor = new Processor();
var compiler = processor.NewXsltCompiler();
compiler.BaseUri=new Uri(Server.MapPath("/"));
var executable = compiler.Compile(new XmlTextReader(new StringReader(xslt_input)));
XPathDocument doc = new XPathDocument(new StringReader(param));
DocumentBuilder db = processor.NewDocumentBuilder();
XdmNode xml;
using (XmlReader xr = XmlReader.Create(new StringReader(param)))
{
xml = db.Build(xr);
}
//xml input
DocumentBuilder builder = processor.NewDocumentBuilder();
builder.BaseUri= new Uri(Server.MapPath("/"));
MemoryStream ms = new MemoryStream();
StreamWriter tw = new StreamWriter(ms);
tw.Write(xml_input);
tw.Flush();
Stream instr = new MemoryStream(ms.GetBuffer(), 0, (int)ms.Length);
XdmNode input = builder.Build(instr);
// Do transformation to a destination
var destination = new DomDestination();
var transformer = executable.Load();
//Set the parameter with xml value
transformer.SetParameter(new QName("", "", param_name), xml);
// Set the root node of the source document to be the initial context node
transformer.InitialContextNode = input;
transformer.Run(destination);
// Get result
return destination.XmlDocument.InnerXml.ToString();
}
The XsltTransformer has a method SetInputStream() that allows you to supply the input as a stream (which indeed you appear to be using).
This post How do I generate a stream from a string? tells you how to create a stream from a string.
I run a method on a service that returns just one line of XML on a string:
<boolean xmlns="http://schemas.microsoft.com/2003/10/Serialization/">true</boolean>
I was trying to deserialize this line this way:
var strXml = "<boolean xmlns='http://schemas.microsoft.com/2003/10/Serialization/'>true</boolean>";
XmlSerializer serializer = new XmlSerializer(typeof(bool));
bool success = false;
using (TextReader reader = new StringReader(strXml))
{
success = (bool)serializer.Deserialize(reader);
}
But at the line
success = (bool)serializer.Deserialize(reader);
An exception is thrown:
There is an error in XML document (1, 2)
There is any clue about what I can do? I'm quite new to XML serialization.
You can use XElement.Parse to parse any individual element:
XElement element = XElement.Parse(strXml);
Sample:
string strXml = #"<boolean xmlns =""http://schemas.microsoft.com/2003/10/Serialization/"">true</boolean>";
bool success = (bool)XElement.Parse(strXml); // true
Try it online
you can just grab the value from the root node and try parsing it as a bool:
//load into XDocument
var doc = XDocument.Parse("<boolean xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/\">true</boolean>");
bool success = bool.Parse(doc.Root.Value); //true
That XML looks like it was created with DataContractSerializer, so use that:
var serializer = new DataContractSerializer(typeof(bool));
using (var sr = new StringReader(xml))
using (var xr = XmlReader.Create(sr))
{
var success = (bool) serializer.ReadObject(xr);
}
Currently I'm using this code to deserialize a file
StreamReader str = new StreamReader(reply);
System.Xml.Serialization.XmlSerializer xSerializer = new System.Xml.Serialization.XmlSerializer(typeof(imginfo));
imginfo res = (imginfo)xSerializer.Deserialize(str);
How should I modify the code if reply is a string and not a path to an xml file?
Basically, you use an XmlReader chained to a StringReader:
imginfo res;
using(var sr = new StringReader(xml)) // "xml" is our string containing xml
using(var xr = XmlReader.Create(sr)) {
res = (imginfo)xSerializer.Deserialize(xr);
}
//... use "res"
or as Anders notes:
imginfo res;
using(var sr = new StringReader(xml)) // "xml" is our string containing xml
res = (imginfo)xSerializer.Deserialize(sr);
}
//... use "res"
Use StringReader instead of StreamReader. No other change needed.
I am bulding up an XDocument and serializing it to a UTF8 string with the following code:
string xmlString = "";
using (MemoryStream ms = new MemoryStream())
{
using (XmlWriter xw = new XmlTextWriter(ms, Encoding.UTF8))
{
doc.Save(xw);
xw.Flush();
StreamReader sr = new StreamReader(ms);
ms.Seek(0, SeekOrigin.Begin);
xmlString = sr.ReadToEnd();
}
}
This worked fine.
I then needed to toggle whether or not the declarator was serialized to the string. I changed the code to this:
string xmlString = "";
using (MemoryStream ms = new MemoryStream())
{
XmlWriterSettings settings = new XmlWriterSettings()
{
OmitXmlDeclaration = !root.IncludeDeclarator,
Encoding = Encoding.UTF8
};
using (XmlWriter xw = XmlTextWriter.Create(ms, settings))
{
doc.Save(xw);
xw.Flush();
StreamReader sr = new StreamReader(ms);
ms.Seek(0, SeekOrigin.Begin);
xmlString = sr.ReadToEnd();
}
}
This throws the following exception on doc.Save(xw):
The prefix '' cannot be redefined from
'' to 'my_schema_here' within the same
start element tag.
I am trying to figure out why the XDoc can be saved if the writer is "new"ed up, but not if it is ".Create"d. Any ideas?
Jordon
I fixed this by adding the namespace to the name of the root element in the XDocument. Still, it's strange that this isn't necessary if "new XmlTextWriter()" is used instead of "XmlTextWriter.Create()" or "XmlWriter.Create()".
Jordon