.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Post New Web Links

How to deserialize with XmlDocument and/or XmlDataProvider?

Posted By:      Posted Date: September 25, 2010    Points: 0   Category :WPF
 

Hi. I have a set of classes set up that I have used in the past to deserialize with XmlSerializer:

	XmlSerializer serializer = new XmlSerializer(typeof(Foo));
	Foo foo = (Foo)serializer.Deserialize(stream);

What I would now like to do is embed that Xml in a Xaml file that is loaded at runtime using an XmlDataProvider:

	<XmlDataProvider x:Key="FooKey" >
		<x:XData>
		 ....
		</x:XData>
	</XmlDataProvider>

I'm loading the Xaml at runtime (it's a ResourceDictionary), extracting the XmlDataProvider and adding a callback for when the data has been loaded and is available:

	ResourceDictionary dictionary = (ResourceDictionary)XamlReader.Load(stream);
	XmlDataProvider provider = dictionary["FooKey"] as XmlDataProvider;
	provider.DataChanged += new EventHandler(provider_DataChanged);

My question is: in my provider_DataChanged handler, how do I deserialize that xml data given that XmlSerializer expects a str


View Complete Post


More Related Resource Links

XmlDataProvider: Bind an XmlDocument with an XmlDataProvider

  

I am trying to use a XmlDocument (xmlDoc) with a XmlDataProvider to bind the XML document to a control.

 

However, I get the error message "The resource 'xmldata' could not be resolved." In code-behind this is how the XML document is loaded with a string at runtime: xmlDoc.LoadXml(e.data)

 

 

Any hints on how to solve the issue would be highly appreciated.

 

Thank you

 

 

<Window x:Class="MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525" > <Window.Resources> <XmlDataProvider x:Key="xmlData" Document="xmlDoc" XPath="./ReportSnapshot" > </XmlDataProvider> </Window.Resources> <Grid Name="grid1" DataContext="xmldoc"> <TextBox Name="textbox1" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto" Text="{Binding Source={StaticResource xmldata}, BindsDirectlyToSource=True, Path=Source, UpdateSourceTrigger=PropertyChanged}"> </TextBox> </Grid> </Window>


XmlDataProvider and XMLDocument loaded as string from code behind

  

I am trying to load an XML string in a XML document and bind this XML document using the XmlDataProvider to a control.

However, I get the error message "The resource 'xmldata' could not be resolved." In code-behind this is how the XML document is loaded with a string at runtime: xmlDoc.LoadXml(e.data)

  

Any hints on how to solve the issue would be highly appreciated.

 

Thank you

 

 

<Window x:Class="MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525" >

 <Window.Resources> <XmlDataProvider x:Key="xmlData" Document="xmlDoc" XPath="./ReportSnapshot" >

</XmlDataProvider>

</Window.Resources>

<Grid Name="grid1" DataContext="xmldoc">

 <TextBox Name="textbox1" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto" Text="{Binding Source={StaticResource xmldata}, BindsDirectlyToSource=True, Path=Source, UpdateSourceTrigger=PropertyChanged}">

</TextBox>

 </Grid>

 </

JSON Deserialize into Entity Framework Object and setting the DataMemberAttribute "Name="

  

Hi,

 

I'm in the process of deserializing a JSON object into an Entity Framework object.  The property names in the JSON do not match up totally with the property names in the Entity Framework Objects. What I'd like to do is set "Name=" on the  "DataContractAttribute" for the table and the "DataMemberAttribute" for the properties in the Designer.cs file.  I tried setting these in the Designer.cs file manually just to see if it would work - which it did (using JSON.Net) but of course when I went into the .edmx designer I lost all my changes.  Is there a way to do this?

 

Thanks in advance


The formatter threw an exception while trying to deserialize the message

  
Hi I got this error when programming in C# 2008 The formatter threw an exception when trying to deserialize the message: Error while trying to deserialize parameter http://tempuri.org/:GetListSitesResponse. The InnerException message was' Error on line 1, position 314. The item 'http://tempuri.org/:anyType' contains data data contract 'http://tempuri.org/:Site'. The deserializer has no knowledge of any type that is assigned to this contract. Add the type corresponding to 'Site' to the list of known types (eg, using the attribute KnownTypeAttribute or adding it to the list of known types passed to DataContractSerializer). '. See InnerException for more information. This happen in my button_click event (this is a project on C# 2008 express windows form application) private void button1_Click(object sender, EventArgs e)         {             SiteDevelopmentReference.Service1SoapClient sd = new SiteDevelopmentReference.Service1SoapClient();             listBox1.Items.AddRange(sd.GetListSites().ToArray());                            } I have a service reference from another project

Deserialize JSON object in C#

  
Hi, I am new to JSON and one of my service is returning JSON object as a string to my application. I need to Deserialize JSON object in C#. My JSON string is in the current format. string str = "{\"candidates\":[{\"address\":\"1580 MARKET ST, SAN FRANCISCO, CA, 94102\",\"location\":{\"x\":-122.42054,\"y\":37.7745960000001},\"score\":40,\"attributes\":{}},{\"address\":\"1576 MARKET ST, SAN FRANCISCO, CA, 94102\",\"location\":{\"x\":-122.420355,\"y\":37.7747030000001},\"score\":40,\"attributes\":{}}]}"; Can anyone please help me how to get all the address, locations, score and attributes from the above string. Thankyou, Ravi.

How could I deserialize a object which is serialized in JAVA??

  
When I try to do it with the code below. FileStream fileStream = new FileStream( "C:\\apps\\user.tmp", FileMode.Open, FileAccess.Read, FileShare.Read);     BinaryFormatter bf=new BinaryFormatter();     pd = (PianoData)bf.Deserialize(fileStream);     System.Console.WriteLine();     fileStream.Close(); Exception occurred as I had excepted. "The input stream is not a valid binary format."   I wonder if I can do it by another way

Serialize / DeSerialize XElement objecs using BinaryFormatter.

  
Hi, I'm having some business objects which contains XElement properties. I have some offline framework which serialize / deserialize using binary formatter. I'm getting the error "Type 'System.Xml.Linq.XElement' in Assembly 'System.Xml.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' is not marked as serializable." when i try to serialize the xelement object I'm getting the XElement serializer error. We are bit too far with design and need to find some work around to solve this issue. The following program should give you the same error behavior. using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Xml.Linq; using System.IO; using System.Runtime.Serialization.Formatters.Binary; namespace XElementBinaryformatter {     public partial class Form1 : Form     {         private BinaryFormatter formatter = new BinaryFormatter();         public Form1()         {             InitializeComponent();         }         private void btnSerialize_Clic

Deserialize xml elements with attributes

  
Hi. How can I deserialize xml elements with attributes to a simple class using XmlSerializer ? Xml contains list of elements as so.     <elementGroups> <element unit="lbs">140</element> <element unit="kts">3040</element> <element unit="m">1003</element> </elementGroups>   The Element class should by like this.     public class Element { [ ????("value")] public decimal Value{ get; set; } [XmlAttribute("unit")] public string Unit{ get; set; } }   is there any elegant way to do this ?  thanks..    

Serialize / DeSerialize XElement objecs using BinaryFormatter.

  
Hi, I'm having some business objects which contains XElement properties. I have some offline framework which serialize / deserialize using binary formatter. I'm getting the error "Type 'System.Xml.Linq.XElement' in Assembly 'System.Xml.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' is not marked as serializable." when i try to serialize the xelement object I'm getting the XElement serializer error. We are bit too far with design and need to find some work around to solve this issue. The following program should give you the same error behavior. using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Xml.Linq; using System.IO; using System.Runtime.Serialization.Formatters.Binary; namespace XElementBinaryformatter {     public partial class Form1 : Form     {         private BinaryFormatter formatter = new BinaryFormatter();         public Form1()         {             InitializeComponent();         }         private void btnSerialize_Clic

Sharepoint Designer issue "could not deserialize object"?

  
Hi there, I'm relatively new to Sharepoint in general but I've got an install of Sharepoint Foundation and I'm working my way through the book "Sharepoint 2010 Development." At any rate, I'm trying to create a workflow in Visio 2010 and then export that workflow into Sharepoint Designer 2010. However, when I try to import the .vwi file into Designer, I get a "Could not deserialize object. The type 'Microsoft.Office.Workflow.Actions.ApprovalTaskProcess' could not be resolved." This, of course, is because in Visio I have a Start Approval Process object.  Is this particular workflow item not available for Sharepoint Foundation? Does anyone have any idea why I'm getting this error? Any feedback is appreciated. Thanks, Jearod

Can serialize but not deserialize class containing an xs:list attribute using XmlSerializer

  
I have a simple serializable class along the lines of: [Serializable] [XmlType] public class MyClass { [XmlAttribute("values")] public int[] Values { get; set; } } If I create an instance of this class with Values set to an empty collection the XmlSerializer class produces this output as expected: <?xml version="1.0" encoding="utf-16" ?> <MyClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" values="" /> However, deserializing this exact output throws a System.FormatException: Input string was not in a correct format. Shouldn't the XmlSerializer be able to deserialize this, since it produced the xml string in the first place?

Re-signed my assembly, now I cannot deserialize objects saved before

  
I have a strange situation about object deserialization. My assemblies all had strong name but signed with different key pair file - I did not realize it is better to have all assemblies signed with the same key pair file before. And now I need to use one single key pair file to resign all assemblies for some other purpose. But After I did that, my program cannot deserialize objects saved by previous version of the assemblies anymore. Use XML object as example, In the XML file, the object is saved with this kind of information, <MyObject version="1" referenceType="MyObject, Assembly1, Version=1.1.0.0, Culture=neutral, PublicKeyToken=f89a7ef07260c910"> <.... omited ... > </MyObject> The problem is that, the Assembly1 is resigned and the public key token of the running assembly does not match the token in the xml file. The same problem happens in my binary objects. Any gurus have some idea to deserialize objects after I resigned the assemblies? My program saved hundreds of objects, I hope there is some solution which will work with all of those objects.    

Timer job intiation error: SharePoint cannot deserialize an object of type

  
Hi All, when i run a timer job (One-Time timer) it has added it to Timer Job definitions in the Central Administration. I have checked the Log file in 12 hive and found the following error..... "SharePoint cannot deserialize an object of type xyz.xyzJob, xyzTimer, Version=1.0.0.0, Culture=neutral, PublicKeyToken=<token> on this machine. This typically occurs because the assembly containing this type is not installed on this machine. In this case, this message can be safely ignored. Otherwise, the assembly needs to be installed on this machine in a location that can be discovered by the .NET Framework." The above error says that the assembly is not added.... but it has been already added to the GAC. Can anyone guide me about the issue and how to resolve that........?

Help!!! WCF:: The formatter threw an exception while trying to deserialize the message

  
I have[ServiceContract]    public interface IBusiness    {        [OperationContract]        [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json)]        bool UpdateLanguage(int languageId, string name, string code);    }public class Business:IBusiness    {        public bool UpdateLanguage(int languageId, string name, string code)        {           //update to database        }    }Add client:$.ajax({ type: "POST", url: "/Services/Business.svc/UpdateLanguage", data: "{'languageId':'" + languageId + "', " + "'name':'" + name + "'," + "'code':'" + code + "'}", contentType: "application/json; charset=utf-8", dataType: "json", processdata: true, success: function (response) { //rebind data here!

add an XML node to an existing XMLdocument

  
I want to add an XML node (locationNode) to an existing XMLdocument (xmldoc)However, I get the error: The node to be inserted is from a different document context.Which makes sense, but then I dont know how I can do what I want.Here's my code:Dim doc As XmlDocument = New XmlDocument()Dim locationNode As XmlNode = doc.CreateElement("location")Dim locationAttribute As XmlAttribute = doc.CreateAttribute("id")locationAttribute.Value = "3"locationNode.Attributes.Append(locationAttribute)'doc.AppendChild(locationNode)Dim titleNode As XmlNode = doc.CreateElement("title")titleNode.AppendChild(doc.CreateTextNode("Opera house"))locationNode.AppendChild(titleNode)xmldoc.AppendChild(locationNode)contents of xmldoc:    <root>    <data>        <compare>            <locations>                <location id="4">                    <title>Empire state building</title>                </location>                <location id=&quo

XMLDocument Save() Method inserting unwanted line breaks

  
(Visual Studio 2005, .NET framework ver. 2.0 sp1, C#)   Hi all - I hope there's a some simple solution for this. I have a SQL Server 2005 (.dtsx) SSIS package file which I open and make a slight change to, then save it back. The problem is that the resulting saved file differs from the original, even if i haven't made any programattical changes at all.   Specifically, if i do something like this:   using System.XML; XmlDocument doc = new XmlDocument();doc.Load(DTSXFile);doc.Save("TEST-COPY_" + DTSXFile);   So I found that even if i completely remove any modifications i was making, and break it down so that all I am doing is simply loading the file, and then turning right around and saving it, I get line breaks inserted for nodes that have empty values...I looked over the entire file, and the issue is not happening if there is a value...only in the case where the value is missing.   a line like this in the source file: <DTS:xProperty DTS:Name="VersionBuild">7</DTS:xProperty>   comes over perfectly after saving as this: <DTS:xProperty DTS:Name="VersionBuild">7</DTS:xProperty>   But, in the source file, a line like this (empty value): <DTS:xProperty DTS:Name="VersionBuild"></DTS:xProperty>   will end up looking like this in the TEST-COPY file after saving: <DTS:xProperty DTS:Name="VersionBuil

returning an xmldocument from a webservice

  
Ive created a webservice that returns an xmldocument[WebMethod]public XmlDocument Invoke(){   //code here}when I add a webreference to a consuming project, the return type is classed as XMLNode, anyone know why ?
Categories: 
ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend