XmlSerializer with custom transform using XSLT - xslt

Is there a way to deserialize a XML stream using XmlSerializer by applying a custom transform defined in a XSLT?

I don't think there is a single API call that would allow that but you could certainly implement that with a few lines along the following approach:
XslCompiledTransform proc = new XslCompiledTransform();
proc.Load("sheet.xsl");
XmlDocument tempResult = new XmlDocument();
using (XmlWriter xw = tempResult.CreateNavigator().AppendChild())
{
proc.Transform("input.xml", null, xw);
xw.Close();
}
XmlSerializer ser = new XmlSerializer(typeof(Foo));
Foo foo = (Foo)ser.Deserialize(new XmlNodeReader(tempResult));

Related

get values from soap response in java

I am calling a web-service method through a web-service client generated by the netbeans IDE.
private String getCitiesByCountry(java.lang.String countryName) {
webService.GlobalWeatherSoap port = service.getGlobalWeatherSoap();
return port.getCitiesByCountry(countryName);
}
So i call this method inside my program,
String b = getWeather("Katunayake", "Sri Lanka");
and it will give me a string output which contains xml data.
String b = getWeather("Katunayake", "Sri Lanka"); = (java.lang.String) <?xml version="1.0" encoding="utf-16"?>
<CurrentWeather>
<Location>Katunayake, Sri Lanka (VCBI) 07-10N 079-53E 8M</Location>
<Time>Jun 22, 2015 - 06:10 AM EDT / 2015.06.22 1010 UTC</Time>
<Wind> from the SW (220 degrees) at 10 MPH (9 KT):0</Wind>
<Visibility> greater than 7 mile(s):0</Visibility>
<SkyConditions> partly cloudy</SkyConditions>
<Temperature> 86 F (30 C)</Temperature>
<DewPoint> 77 F (25 C)</DewPoint>
<RelativeHumidity> 74%</RelativeHumidity>
<Pressure> 29.74 in. Hg (1007 hPa)</Pressure>
<Status>Success</Status>
</CurrentWeather>
How may i get the value of <Location>,<SkyConditions>,<Temperature>.
You can go for XPath if you need only these 3 values. Otherwise, DOM reads the entire document. It is very easy to write XPath expressions those directly fetch the node to read values.
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = null;
try {
builder = factory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
String xml = ...; // <-- The XML SOAP response
Document xmlDocument = builder.parse(new ByteArrayInputStream(xml.getBytes()));
XPath xPath = XPathFactory.newInstance().newXPath();
String location = xPath.compile("/CurrentWeather/Location").evaluate(xmlDocument);
String skyCond = xPath.compile("/CurrentWeather/SkyConditions").evaluate(xmlDocument);
String tmp = xPath.compile("/CurrentWeather/Temperature").evaluate(xmlDocument);
If, you need to fetch many XML nodes and frequently, then go for DOM.
One way is using a DOM parser, using http://examples.javacodegeeks.com/core-java/xml/java-xml-parser-tutorial as a guide:
String b = getWeather("Katunayake", "Sri Lanka");
InputStream weatherAsStream = new ByteArrayInputStream(b.getBytes(StandardCharsets.UTF_8));
DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = fac.newDocumentBuilder();
org.w3c.dom.Document weatherDoc = builder.parse(weatherAsStream);
String location = weatherDoc.getElementsByTagName("Location").item(0).getTextContent();
String skyConditions = weatherDoc.getElementsByTagName("SkyConditions").item(0).getTextContent();
String temperature = weatherDoc.getElementsByTagName("Temperature").item(0).getTextContent();
This has no exception handling and might break if there are more than one elements with the same name, but you should be able to work from here.

Serializing List<MemoryStream> to a file using a standard .NET class

Writing a WP8 Silverlight app. Is there a standard .NET technique available in this environment I can use to serialize an object like this
private static List<MemoryStream> MemoryStreamList = new List<MemoryStream>();
to save it to a file and restore it later?
I tried to use DataContractJsonSerializer for this which is good to serialize a List of simple custom objects, but it fails for List (I get System.Reflection.TargetInvocationException).
I would suggest converting your list to a list of byte arrays before persisting and then you should be able to serialize. Of course this comes with some overhead at deserialization as well.
Serialization part:
byte[] bytes = null;
var newList = MemoryStreamList.Select(x => x.ToArray()).ToList();
XmlSerializer ser = new XmlSerializer(newList.GetType());
using (var ms = new MemoryStream())
{
ser.Serialize(ms, newList);
//if you want your result as a string, then uncomment to lines below
//ms.Seek(0, SeekOrigin.Begin);
//using (var sr = new StreamReader(ms))
//{
//string serializedStuff = sr.ReadToEnd();
//}
//else you can call ms.ToArray() here and persist the byte[]
bytes = ms.ToArray();
}
Deserialization part:
using (var ms = new MemoryStream(bytes))
{
var result = ser.Deserialize(ms) as List<byte[]>;
}

How to populate XML node values in Grid view in Asp.net?

I am using a thirdparty webservice. I got the response in XML format.
Now, i have to show the XML node values in grid view.
The following code i tried so far.
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
//Label2.Text = reader.ReadToEnd();
XmlDocument xml = new XmlDocument();
xml.Load(reader);
XmlNamespaceManager ns = new XmlNamespaceManager(xml.NameTable);
ns.AddNamespace("ms", "http://webservices.amazon.com/AWSECommerceService/2005-10-05");
XmlNode image = xml.SelectSingleNode("//ms:URL", ns);
XmlNode FormattedPrice = xml.SelectSingleNode("//ms:FormattedPrice", ns);
Now, i want to show the values of XMLnode value in grid view.
Please inform me, if you need more information.
Thanks in advance.
You can use an XMLDataSourcefor that:
http://www.codeproject.com/Articles/10898/Introduction-to-XMLDataSource-control-in-ASP-NET-2
Best regards.
Solution:
Instead of Get the HttpResponse in xmldocument.
I used XNamespace and XDocument.
XNamespace ns = "http://webservices.amazon.com/AWSECommerceService/2005-10-05"; // Linq
XDocument xd = XDocument.Load(response.GetResponseStream());
Then Use Linq to Read all Vlaues. Example:
var Image = xd.Descendants(ns + "Items").Elements(ns + "Item").Select(img => img.Elements(ns + "MediumImage").Select(img1 => (string)img1.Element(ns + "URL")).FirstOrDefault() ?? "Null").ToList();

Dynamic XML code generation in C++

I would like to transform some C++ objects of classes of my own into XML code. I guess there are several libraries which provide C++ to XML-mapping, but I would like to keep the library overhead simple and craft something of my own.
What would be an appropriate approach to generate XML building? In Java there are annotations which could be use to dynamaically generate the XML. Maybe the template mechanism?
I am using TinyXML so far. I really enjoy using it.
Here is an example, which I would like to be generated:
std::string XMLBuilder::buildThreadInformation(vector<threadinfo> threadinfos) {
TiXmlDocument document;
TiXmlDeclaration *declaration = new TiXmlDeclaration("1.0", "", "");
TiXmlElement *messageWrapElement = new TiXmlElement("message");
TiXmlElement *threadsElement = new TiXmlElement("threads");
messageWrapElement->LinkEndChild(threadsElement);
std::string numberString;
for (vector<threadinfo>::const_iterator it = threadinfos.begin(); it
!= threadinfos.end(); ++it) {
TiXmlElement *threadElement = new TiXmlElement("thread");
threadsElement->LinkEndChild(threadElement);
TiXmlElement *threadNumberElement = new TiXmlElement("number");
threadElement->LinkEndChild(threadNumberElement);
numberString = boost::lexical_cast<std::string>((*it).thread_number);
TiXmlText *threadNumber = new TiXmlText(numberString.c_str());
threadNumberElement->LinkEndChild(threadNumber);
TiXmlElement *threadNameElement = new TiXmlElement("name");
threadElement->LinkEndChild(threadNameElement);
TiXmlText *threadName = new TiXmlText((*it).name.c_str());
threadNameElement->LinkEndChild(threadName);
}
document.LinkEndChild(declaration);
document.LinkEndChild(messageWrapElement);
TiXmlPrinter printer;
document.Accept(&printer);
std::string result = printer.CStr();
return result;
}
The class threadinfo would consist of int number and std::string name.
RapidXML is also pretty easy to use and can create dynamic xml for you.

SharePoint web services: test if file exists

I'm using SharePoint web services in C#. I have my code working to check files and check them out using the Lists web service. I need to test to see if a file exists; I can find lots of examples for doing this using the object model API, but I can't seem to find a straightforward way of doing this using web services.
Try the Lists.GetListItems with a suitable CAML query.
A CAML query like
<Query><Where><Eq><FieldRef Name="FileLeafRef" /><Value Type="Text">Filename.rtf</Value></Eq></Where></Query>
should work; the field 'FileLeafRef' is where the filename is stored.
This code may do, it's a little rough, but demonstrates how to get a list of files based on the title.
public static bool PageExists(string listName, string webPath, string pageTitle)
{
string pageId = "";
IntranetLists.Lists lists = new IntranetLists.Lists();
lists.UseDefaultCredentials = true;
lists.Url = webPath + "/_vti_bin/lists.asmx";
XmlDocument doc = new XmlDocument();
doc.LoadXml("<Document><Query><Where><Contains><FieldRef Name=\"Title\" /><Value Type=\"Text\">" + pageTitle + "</Value></Contains></Where></Query><ViewFields /><QueryOptions /></Document>");
XmlNode listQuery = doc.SelectSingleNode("//Query");
XmlNode listViewFields = doc.SelectSingleNode("//ViewFields");
XmlNode listQueryOptions = doc.SelectSingleNode("//QueryOptions");
Guid g = GetWebID(webPath);
XmlNode items = lists.GetListItems(listName, string.Empty, listQuery, listViewFields, string.Empty, listQueryOptions, g.ToString());
}
return items.Count > 0;
}
public static XmlNodeList XpathQuery(XmlNode xmlToQuery, string xPathQuery)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlToQuery.OuterXml);
XmlNamespaceManager mg = new XmlNamespaceManager(doc.NameTable);
mg.AddNamespace("sp", "http://schemas.microsoft.com/sharepoint/soap/");
mg.AddNamespace("z", "#RowsetSchema");
mg.AddNamespace("rs", "urn:schemas-microsoft-com:rowset");
mg.AddNamespace("y", "http://schemas.microsoft.com/sharepoint/soap/ois");
mg.AddNamespace("w", "http://schemas.microsoft.com/WebPart/v2");
mg.AddNamespace("d", "http://schemas.microsoft.com/sharepoint/soap/directory");
return doc.SelectNodes(xPathQuery, mg);
}
I also had similiar problems with this.
I have tried the following FieldRefs without success: "Name", "FileLeafRef" and "LinkFilenameNoMenu".
The post located at http://www.johanolivier.blogspot.com details what I had to do to get it working.