I have classes generated from xsd that i would like to use to create an xml to send over the wire. I just want to create the document in memory, convert it to string/byte[] and send it. I was under the impression that once the classes are populated, i could just do a tostring() and it would return the entire document out. That doesn't seem to be the case... What am i doing wrong here?
#event myEvent = new #event();
myEvent.name = "AddProgram";
myEvent.version = 8.0M;
DateTime myDateTime = new DateTime();
myDateTime = DateTime.Now;
myEvent.time = myDateTime;
detail myDetail = new detail();
myDetail.name = "Program1"
myEvent.detail = myDetail;
Controller controller = new Controller();
controller.actionSpecified = true;
controller.action = ControllerAction.Create;
myDetail.Controller = controller;
String xmlString = myEvent.ToString(); //this is where i would expect a string.
all i get out of this is: "event"
I am not sure where you got your information that ToString() would give you an xml representation of the class but that is not true. What you should do is refer to this article about XML serialization.
http://msdn.microsoft.com/en-us/library/58a18dwa(v=vs.110).aspx
If you have a class of Type event then you would need to do the following to serialize it to XML, Also as a small tidbit I would stay away from using Key words as class or variable definitions if at all possible, but if you're not in control of that then your hands are tied.
#event myEvent = new #event();
myEvent.name = "AddProgram";
myEvent.version = 8.0M;
string xmlIWant= "";
System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(#event);
using (StringWriter writer = new StringWriter())
{
x.Serialize(writer, myEvent);
xmlIWant = writer.ToString();
}
Related
TLDR; Please either confirm that the 2nd code snippit is the accepted method for creating a CustomXmlPart or show me another less tedious method.
So I'm trying to embed some application data in some of the elements in a .pptx that I'm modifying using the OpenXmlSDK.
To explain briefly, I need to embed an chart code into each image that is loaded into the presentation. It's so that the presentation can be re-uploaded and the charts can be generated again then replaced using the newest data.
Initially I was using Extended Attributes on the OpenXmlElement itself:
//OpenXmlDrawing = DocumentFormat.OpenXml.Drawing
// there's only one image per slide for now, so I just grab the blip which contains the image
OpenXmlDrawing.Blip blip = slidePart.Slide.Descendants<OpenXmlDrawing.Blip>().FirstOrDefault();
//then apply the attribute
blip.SetAttribute(new OpenXmlAttribute("customAttribute", null, customAttributeValue));
The issue with that being, when the .pptx is edited in PowerPoint 2013, it strips out all the Extended Attributes.
SO.
I've read in multiple places now that the solution is to use a CustomXmlPart.
So I was trying to find how to do it.. and it was looking like it would require me to have a separate file for each CustomXmlPart to feed into the part. Ex/
var customXmlPart = slidePart.AddCustomXmlPart(CustomXmlPartType.CustomXml);
using (FileStream stream = new FileStream(fileName, FileMode.Open))
{
customXmlPart.FeedData(stream);
}
^ and that would need to be repeated with a different file for each CustomXmlPart. Which then means I'd likely just have to have a template file containing a skeleton custom XML part, and then dynamically fill in its contents for each individual slide before feeding it into the custom xml part.
It seems like a heck of a lot of work just to put in a little custom attribute. But I haven't been able to find any alternative methods.
Can anyone please either confirm that this is indeed the way I should do it, or point me in another direction? Greatly appreciated.
The answer is yes! :)
public class CustomXMLPropertyClass
{
public string PropertyName { get; set; }
public string PropertyValue { get; set; }
}
private static void AddCustomXmlPartCustomPropertyToSlidePart(string propertyName, string propertyValue, SlidePart part)
{
var customXmlPart = part.AddCustomXmlPart(CustomXmlPartType.CustomXml);
var customProperty = new CustomXMLPropertyClass{ PropertyName = propertyName, PropertyValue = propertyValue };
var serializer = new System.Xml.Serialization.XmlSerializer(customProperty.GetType());
var stream = new MemoryStream();
serializer.Serialize(stream, customProperty);
var customXml = System.Text.Encoding.UTF8.GetString(stream.ToArray());
using ( var streamWriter = new StreamWriter(customXmlPart.GetStream()))
{
streamWriter.Write(customXml);
streamWriter.Flush();
}
}
and then to get it back out:
private static string GetCustomXmlPropertyFromCustomXmlPart(CustomXmlPart customXmlPart)
{
var customXmlProperty = new CustomXMLPropertyClass();
string xml = "";
using (var stream = customXmlPart.GetStream())
{
var streamReader = new StreamReader(stream);
xml = streamReader.ReadToEnd();
}
using (TextReader reader = new StringReader(xml))
{
var serializer = new System.Xml.Serialization.XmlSerializer(typeof(customXmlProperty));
customXmlProperty = (CustomXMLPropertyClass)serializer.Deserialize(reader);
}
var customPropertyValue = customXmlProperty.PropertyValue;
return customPropertyValue;
}
You could also try custom properties. Custom XML files are meant for complex objects, and it sounds like you only need to store simple information.
There are lots of examples on the web of transforming an XML file to a different format using an XSLT file, like the following:
XslTransform myXslTransform = new XslTransform();
XsltSettings myXsltSettings = new XsltSettings();
myXsltSettings.EnableDocumentFunction = true;
myXslTransform.Load("transform.xsl");
myXslTransform.Transform("input.xml", "output.xml");
However this is only a partial answer, I would like to be able to get the XML input data from a web form and use that as the input xml data instead of an '.xml' file, but have not found any concrete examples. Using Visual Studio I see Load methods that accept XmlReader objects as parameters but I do not know how to create one of those using the data from a form and TextBox control. It would be very helpful if someone could provide an example of transforming XML using form data instead of an input file.
Create a class and populate an instance of this class during postback from your form data and serialize it ( convert it to xml)
Here is console example for you
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
namespace Stackoverflow
{
public class Program
{
static void Main(string[] args)
{
var p = new Person
{
FirstName = "Daniel", /// in your case you get it from the form
LastName = "Endeg"
};
var x = new XmlSerializer(p.GetType());
x.Serialize(Console.Out, p);
Console.WriteLine();
Console.ReadLine();
}
}
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
}
Please note that XslTransform is obsolete since .NET 2.0, you should use XslCompiledTransform instead. And if you want to use XslSettings then make sure you pass them in to the XslCompiledTransform's Load method (e.g. http://msdn.microsoft.com/en-us/library/ms163425.aspx), simply creating it does not make sense.
As for parsing XML you have in a string variable or property (like the Text property of a TextBox) you have lots of options, you can use an XmlReader over a StringReader e.g.
XslCompiledTransform proc = new XslCompiledTransform();
proc.Load("sheet.xsl");
using (StringReader sr = new StringReader(TextBox1.Text))
{
using (XmlReader xr = XmlReader.Create(sr))
{
proc.Transform(xr, null, Response.Output);
}
}
Or you can create an XPathDocument or XmlDocument or XDocument from the string and use an overload of the Transform method that takes an IXPathNavigable as the first argument.
Ok, with some help from Visual Studio auto-complete which lists the parameters for constructors and methods, I was able to complete a working answer to the problem above, using strings for input and output in an Xslt transform operation. Yay. The example answer below assumes you have three strings containing the Xslt text data and the input Xml text data and output Xml data:
string XsltText;
string InputXML;
string OutputXml;
// define the xslt from a string
TextReader myXsltText = new StringReader(XsltText);
XmlReader myXslt = new XmlTextReader(myXsltText);
// define the input xml from a string
TextReader myXmlText = new StringReader(InputXML);
XmlReader myInputXml = new XmlTextReader(myXmlText);
// define the output XmlWriter for the results of the transform
TextWriter myOutputXmlTextWriter = new StringWriter();
XmlWriter myOutputXml = new XmlTextWriter(myOutputXmlTextWriter);
XslCompiledTransform myXslTransform = new XslCompiledTransform();
XsltSettings myXsltSettings = new XsltSettings();
myXsltSettings.EnableDocumentFunction = true;
myXslTransform.Load(myXslt);
myXslTransform.Transform(myInputXml, myOutputXml);
// the result from the transform comes from the TextWriter object
OutputXml = myOutputXmlTextWriter.ToString();
// clean up writers
myOutputXml.Flush();
myOutputXmlTextWriter.Close();
myOutputXml.Close();
To get this code working with a web form, all you have to do is get the strings from the value (Text) of the form elements (controls), for the input XMl and Xslt you could use TextBox controls, and to display the results you could use a label, all very useful, if anyone has a better answer please feel free to let me know.
I'm new to serialization.I need to send a Serialized object from a one web site to another web site.
i'm using following serialization code in my first web site
private void Serialize()
{
Cuser cat = new Cuser();
cat.UserNO = 1;
cat.UerName = "chamara";
cat.Passwod = "123";
XmlSerializer ser = new XmlSerializer(cat.GetType());
StringBuilder sb = new StringBuilder();
StringWriter writer = new StringWriter(sb);
ser.Serialize(writer, cat);
XmlDocument doc = new XmlDocument();
doc.LoadXml(sb.ToString());
Response.Redirect("https://site1.com.au");
}
now i need to retrieve(deserialize) these data from site1.com.i have the deserialization code.i need to know how can i transfer this object? and am i using serialization for the correct purpose? hope my explanation is clear enough to understand the issue.
There is some chance that you want to render data in a form on site-1 and automatically post the form to site-2 with client side script.
how can display a string from a rest webservice in windows forms my xml looks like this:
<string>whatever</string>
How can you display that in a textbox in win forms?
If I try
string uri = string.Format("etc/{0}/{1} Sad.Text, Happy.Text");
XDocument xDoc = XDocument.Load(uri);
string mystring = xDoc.Element("String").Value;
textBox1.Text = mystring;
You get an object reference error?
XML elements are case-sensitive. Try,
string mystring = xDoc.Element("string").Value;
A better way to solve the problem is to not use XML to return a simple string. The media type text/plain is designed to do that. If you are using Microsoft's ASP.NET Web API just return
return new HttpResponseMessage() {
Content = new StringContent("etc/{0}/{1} Sad.Text, Happy.Text")
};
and on the client (using this http://nuget.org/Packages/system.net.http) do,
var httpClient = new HttpClient();
textBox1.Text = httpClient.GetAsync(uri).Result.Content.ReadAsString();
I would use XmlSerializer to get the information out of XML returned by the web service. I am assuming that your XML is just in a string. You could do something like this for your simple example, but this would also work for more complex objects returned by a REST web service.
XmlSerializer xs = new XmlSerializer ( typeof ( string ) );
MemoryStream memoryStream = new MemoryStream(StringToUTF8ByteArray(restResult));
XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
string textBoxVal = xs.Deserialize(memoryStream);
I have this code:
public class Hero
{
XmlReader Reader = new XmlTextReader("InformationRepositories/HeroRepository/HeroInformation.xml");
XmlReaderSettings XMLSettings = new XmlReaderSettings();
public ImageSource GetHeroIcon(string Name)
{
XMLSettings.IgnoreWhitespace = true;
XMLSettings.IgnoreComments = true;
Reader.MoveToAttribute(" //I'm pretty much stuck here.
}
}
And this is the XML file I want to read from:
<?xml version="1.0" encoding="utf-8" ?>
<Hero>
<Legion>
<Andromeda>
<HeroType>Agility</HeroType>
<Damage>39-53</Damage>
<Armor>3.1</Armor>
<MoveSpeed>295</MoveSpeed>
<AttackType>Ranged(400)</AttackType>
<AttackRate>.75</AttackRate>
<Strength>16</Strength>
<Agility>27</Agility>
<Intelligence>15</Intelligence>
<Icon>Images/Hero/Andromeda.gif</Icon>
</Andromeda>
</Legion>
<Hellbourne>
</Hellbourne>
</Hero>
I'm tring to get the ,/Icon> element.
MoveToAttribute() won't help you, because everything in your XML is elements. The Icon element is a subelement of the Andromeda element.
One of the easiest ways of navigating an XML document if you're using the pre-3.5 xml handling is by using an XPathNavigator. See this example for getting started, but basically you just need to create it and call MoveToChild() or MoveToFollowing() and it'll get you to where you want to be in the document.
XmlDocument doc = new XmlDocument();
doc.Load("InformationRepositories/HeroRepository/HeroInformation.xml");
XPathNavigator nav = doc.CreateNavigator();
if (nav.MoveToFollowing("Icon",""))
Response.Write(nav.ValueAsInt);
Note that an XPathNavigator is a forward only mechanism, so it can be problematic if you need to do looping or seeking through the document.
If you're just reading XML to put the values into objects, you should seriously consider doing this automatically via object serialization to XML. This would give you a painless and automatic way to load your xml files back into objects.
Mark your attributes in your object according to the element you want to load them to:
See: http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlattributeattribute.aspx
If, for some reason, you can't do this to your current object, consider making a bridge object which mirrors your original object and add a AsOriginal() method which returns the Original Object.
Working off the msdn example:
public class GroupBridge
{
[XmlAttribute (Namespace = "http://www.cpandl.com")]
public string GroupName;
[XmlAttribute(DataType = "base64Binary")]
public Byte [] GroupNumber;
[XmlAttribute(DataType = "date", AttributeName = "CreationDate")]
public DateTime Today;
public Group AsOriginal()
{
Group g = new Group();
g.GroupName = this.GroupName;
g.GroupNumber = this.GroupNumber;
g.Today = this.Today;
return g;
}
}
public class Group
{
public string GroupName;
public Byte [] GroupNumber;
public DateTime Today;
}
To Serialize and DeSerialize from LINQ objects, you can use:
public static string SerializeLINQtoXML<T>(T linqObject)
{
// see http://msdn.microsoft.com/en-us/library/bb546184.aspx
DataContractSerializer dcs = new DataContractSerializer(linqObject.GetType());
StringBuilder sb = new StringBuilder();
XmlWriter writer = XmlWriter.Create(sb);
dcs.WriteObject(writer, linqObject);
writer.Close();
return sb.ToString();
}
public static T DeserializeLINQfromXML<T>(string input)
{
DataContractSerializer dcs = new DataContractSerializer(typeof(T));
TextReader treader = new StringReader(input);
XmlReader reader = XmlReader.Create(treader);
T linqObject = (T)dcs.ReadObject(reader, true);
reader.Close();
return linqObject;
}
I don't have any example code of Serialization from non-LINQ objects, but the MSDN link should point you in the right direction.
You can use linq to xml:
public class XmlTest
{
private XDocument _doc;
public XmlTest(string xml)
{
_doc = XDocument.Load(new StringReader(xml);
}
public string Icon { get { return GetValue("Icon"); } }
private string GetValue(string elementName)
{
return _doc.Descendants(elementName).FirstOrDefault().Value;
}
}
you can use this regular exspression "<Icon>.*</Icon>" to find all the icons
then just remove the remove the tag, and use it....
would be a lot shorter
Regex rgx = new Regex("<Icon>.*</Icon>");
MatchCollection matches = rgx.Matches(xml);
foreach (Match match in matches)
{
string s= match.Value;
s= s.Remove(0,6)
s= s.Remove(s.LastIndexOf("</Icon>"),7);
console.Writeline(s);
}