Get XML String in PHP with URL - c#

I'm really new to the job as a web developer and I have a Problem that I cant solve alone, also I can't find any answers which fit my Problem.
So this is the Construct, I have a PHP Page with this Code:
<?php
$url = 'http://myserver.de/list.aspx';
$xml = new SimpleXMLElement($url);
$name = $xml->List->member->name;
?>
And I got this C#-Code from an aspx-project (list.aspx):
StringBuilder xmlBuilder = new StringBuilder();
xmlBuilder.Append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
xmlBuilder.Append("<List>");
foreach (var nameandplz in fullname.Zip(plz, Tuple.Create))
{
xmlBuilder.Append("<member>");
xmlBuilder.Append("<name>" + nameandplz.Item1 + "</name>");
xmlBuilder.Append("<postcalcode>" + nameandplz.Item2 + "</postalcode>");
xmlBuilder.Append("</member>");
}
xmlBuilder.Append("</List>");
Context.Response.ContentType = "text/xml";
Context.Response.BinaryWrite(Encoding.UTF8.GetBytes(xmlBuilder.ToString()));
Context.Response.End();
So I just use the StringBuilder to build a String with XML.
fullname and plz are listed.
In my PHP-CIde i call the URL and the Problem is that the SimpleXMLElement doesnt write the XML-Code into the $xml.
I tried everything, i called the URL manually and the XML File is displayed correctly.
Do I use the wrong format to get the XML File per SimpleXMLElement?

To get the data from the URL you must set $data_is_url = true according to the PHP Documentation ( http://php.net/manual/fr/simplexmlelement.construct.php ); so XMLElement try to build an XML from the string given.
You can use the function libxml_get_errors to get XML errors.
So here a code that will get the content from the URL :
<?php
$url = 'http://myserver.de/list.aspx';
$xml = new SimpleXMLElement($url, 0, true);
$name = $xml->List->member->name;
Caution : you access List / Member / Name without testing if List Member or Name exists.

Related

C# - Check URL is valid for TemplateString

I'm currently using a TemplateString to load an image with a link, where {Url} is the file name obtained from the database.
Here is the code I use, as a reference:
Ext.Net.TemplateColumn TheColumn = new Ext.Net.TemplateColumn();
TheColumn.Text = "Image";
TheColumn.DataIndex = "Url";
TheColumn.Align = Alignment.Center;
TheColumn.Flex = 1;
TheColumn.MinWidth = 70;
TheColumn.TemplateString = "<a href='http://example.com/{Url}' data-lightbox='{Url}'><img style='width:60px;height:60px;' src='http://example.com/{Url}'/></a>";
What I would like to do is that I could check if the requested image exists, and if it doesn't, I use an alternative TemplateString instead.
Since I'm using jQuery, I´m leaving the tag in case. The project is an ASP.NET website.

How to convert XMLDocument type to string in order to show the result in a label

I'm trying to show weather information on my website from world weather online. I'm using VS2012 with c# to create this.
I could able to retrieve data from world weather online to a function under a XMLDocument type variable "WP_XMLdoc".
Take a look at the code below:
public static XmlDocument WeatherAPI(string sLocation)
{
HttpWebRequest WP_Request;
HttpWebResponse WP_Response = null;
XmlDocument WP_XMLdoc = null;
String Value;
string sKey = "xxxxxxxxxxxxxxxxxxxxxxxxx"; //The API key generated by World Weather Online
string sRequestUrl = "http://api.worldweatheronline.com/free/v1/weather.ashx?format=xml&"; //The request URL for XML format
try
{
//Here we are concatenating the parameters
WP_Request = (HttpWebRequest)WebRequest.Create(string.Format(sRequestUrl + "q=" + sLocation + "&key=" + sKey));
WP_Request.UserAgent = #"Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.8.1.4) Gecko/20070515 Firefox/2.0.0.4";
//Making the request
WP_Response = (HttpWebResponse)WP_Request.GetResponse();
WP_XMLdoc = new XmlDocument();
//Assigning the response to our XML object
WP_XMLdoc.Load(WP_Response.GetResponseStream());
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
WP_Response.Close();
return WP_XMLdoc;
}
}
So, now I just want to take XML data from "WP_XMLdoc" variable and show few details like temp_c, windspeed, time etc in my labels.
How can I do that?
The XML data that rest under "WP_XMLdoc" is given below:
<?xml version="1.0" encoding="UTF-8"?>
<data>
<request>
<type>City</type>
<query>London, United Kingdom</query>
</request>
<current_condition>
<observation_time>04:17 AM</observation_time>
<temp_C>17</temp_C>
<temp_F>63</temp_F>
<weatherCode>143</weatherCode>
<weatherIconUrl>
<![CDATA[http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0006_mist.png]]>
</weatherIconUrl>
<weatherDesc>
<![CDATA[Mist]]>
</weatherDesc>
<windspeedMiles>0</windspeedMiles>
<windspeedKmph>0</windspeedKmph>
<winddirDegree>62</winddirDegree>
<winddir16Point>ENE</winddir16Point>
<precipMM>0.0</precipMM>
<humidity>94</humidity>
<visibility>2</visibility>
<pressure>1010</pressure>
<cloudcover>50</cloudcover>
</current_condition>
<weather>
<date>2014-09-19</date>
<tempMaxC>28</tempMaxC>
<tempMaxF>82</tempMaxF>
<tempMinC>14</tempMinC>
<tempMinF>57</tempMinF>
<windspeedMiles>5</windspeedMiles>
<windspeedKmph>8</windspeedKmph>
<winddirection>SSE</winddirection>
<winddir16Point>SSE</winddir16Point>
<winddirDegree>149</winddirDegree>
<weatherCode>356</weatherCode>
<weatherIconUrl>
<![CDATA[http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0010_heavy_rain_showers.png]]>
</weatherIconUrl>
<weatherDesc>
<![CDATA[Moderate or heavy rain shower]]>
</weatherDesc>
<precipMM>8.3</precipMM>
</weather>
</data>
Please help!
Assuming that your existing code successfully load the XML data to XmlDocument object, we can then use SelectSingleNode() passing suitable XPath expression as argument to get any particular part of the XML document. For example, to get <temp_C> value :
string temp_c = WP_XMLdoc.SelectSingleNode("/data/current_condition/temp_C")
.InnerText;
Another option is using newer XML API, XDocument. It has Load() method which functionality is similar to XmlDocument.Load() :
XDocument WP_XMLdoc = XDocument.Load(WP_Response.GetResponseStream());
Using this approach, we can simply cast XElement to string to get it's value :
string temp_c = (string)WP_XMLdoc.XPathSelectElement("/data/current_condition/temp_C");
Try something like this, as an example:
var str = #"<your xml here>";
XDocument xdoc = XDocument.Parse(str);
var output = new List<string>();
foreach (var element in xdoc.Element("data").Element("current_condition").Elements())
{
output.Add(string.Format("{0} : {1}",element.Name, element.Value.ToString()));
}
This would traverse the properties of the current_condition node, you can adjust as necessary to extract what you need.
Ok, according to your answer in comments I believe you need to show multiple columns of data.
Best option would be to use a GridView to populate your XML data using ADO.net. It's bit easy.
Have a look at this SO thread

How do I open XML from link in razor?

The task is quite simple, connect to another webservice using XML.
In the current pages (classic ASP) we use the following code:
zoekpcode=UCASE(Request.Querystring("zoekpcode")) <-- postal-code
zoeknr=Request.Querystring("zoeknr") <-- house-number
PC=Trim(Replace(zoekpcode," ",""))
NR=Trim(Replace(zoeknr," ",""))
strGetAddress="https://ws1.webservices.nl/rpc/get-simplexml/addressReeksPostcodeSearch/*~*/*~*/" & PC & NR
set xml = Server.CreateObject("Microsoft.XMLHTTP")
xml.open "GET", strGetAddress , false
xml.send ""
strStatus = xml.Status
If Len(PC)>5 and Len(NR)>0 Then
strRetval = Trim(xml.responseText)
End If
set xml = nothing
'Do something with the result string
One of the possible links could be: https://ws1.webservices.nl/rpc/get-simplexml/addressReeksPostcodeSearch/~/~/1097ZD49
Currently I'm looking for a way to do this in razor (C#), but all I seem to be able to find on Google is how to do it in JavaScript
I've tried (most combinations of) the following terms:
razor
xmlhttp
comobject
XML from url
-javascript
Results were mostly about JavaScript or razorblades.
Based on other result (like in the search comobjects in razor) it seems that comobject aren't available in Razor.
I did find this question (How to use XML with WebMatrix razor (C#)) on stackoverflow that seems to answer my question (partially), but is it also possible with a link to an external system (the mentioned web-service)?
I have covered the consumption of Web Services in Razor web pages here: http://www.mikesdotnetting.com/Article/209/Consuming-Feeds-And-Web-Services-In-Razor-Web-Pages.
If your web service is a SOAP one, you are best off using Visual Studio (the free Express editions is fine) to add a service reference and then work from there. Otherwise you can use Linq To XML to load the XML directly into an XDocument as in the ATOM example in the article:
var xml = XDoxument.Load("https://ws1.webservices.nl/rpc/get-simplexml/blah/blah");
Then use the System.Xml.Linq APIs to query the document.
With the help of Ralf I came to the following code:
public static XmlDocument getaddress(string pcode, string number){
string serverresponse = "";
string getlocation = "https://ws1.webservices.nl/rpc/get-simplexml/addressReeksPostcodeSearch/*~*/*~*/" + Request.QueryString["PCODE"] + Request.QueryString["NR"];
HttpWebRequest req = (HttpWebRequest) WebRequest.Create(getlocation);
using (var r = req.GetResponse()) {
using (var s = new StreamReader(r.GetResponseStream())) {
serverresponse = s.ReadToEnd();
}
}
XmlDocument loader = new XmlDocument();
loader.LoadXml(serverresponse);
return loader;
}
public static string getvalue(XmlDocument document, string node){
string returnval = "";
var results = document.SelectNodes(node);
foreach(XmlNode aNode in results){
returnval = returnval + "," + aNode.InnerText;
}
return returnval.Substring(1);
}

How to return video (flv) path to display in flowplayer?

I would like to integrate flowplayer in ASP mvc 3 application.
I'm using SQL Server 2008. Database contains path to files as well which are stored in folder. I wrote library which is able to convert video to flv. Now i would like to use this video in page.
Does anyone have knowledge how to implement that?
I found the flowplayer sample code.
http://flowplayer.org/docs/
But I'm looking for codebehind solution (C#) how to implement something like that (how to return path to video).
If anyone have some code I'll be grateful for help.
Please take a look.
public string FindMusicByID(int musicID)
{
var pathh = from plik in _data.musicMusicTables
where plik.musicMusicID == musicID
select new PathToFile { PathFile = plik.musicMusicPath };
return pathh.ToString();
}
This is the linq part code which i'm using. FindMusicByID(int musicID) return path to .flv file. I'm looking for how to send output filepath to webpage. I would like to use this path in flowplayer.
<div class="flowplayer" data-engine="flash"> <video src="some path"></video>
Fox example this is my ouptut path d:\file.flv
I suppose that it's necessary to send output to JavaScript.
How can i insert path into flowplayer by ID?
I'm not sure what you are asking for, but if you want to know how to return .flv file for your player you just need Action that return FileStremResult using this mimetype: video/x-flv
Something along the lines of:
public string FindMusicByID(int musicID)
{
var pathh= from plik in _data.musicMusicTables
where plik.musicMusicID == musicID
select new PathToFile { PathFile = plik.musicMusicPath };
var cd = new System.Net.Mime.ContentDisposition {
FileName = "filename",
Inline = false
};
Response.AppendHeader("Content-Disposition", cd.ToString());
return File(path, asset.AssetType.MimeType);
}

Update a RichTextBox on Sp2010 using Windows Forms & ListService.UpdateListItems Method

I'm having an issue updating a RichText box on a SharePoint 2010 list.
_batchElement.InnerXml =
string.Format(
"<Method ID='1' Cmd='New'><Field RichText='True' Name='Other_x0020_Items_x0020_of_x0020'>{0}</Field><Field Name='Overall_x0020_rating_x0020_of_x0'>{1}</Field><Field Name='Do_x0020_you_x0020_wish_x0020_to'>{2}</Field></Method>",
add_Report_Details.Rtf,
arrText,
addreportwish);
And the code to trigger the update:
ListService.UpdateListItems(ListName, _batchElement);
But, given that this xml element cannot have anything starting with a \ it doesn't want to work.
I have tried HTML as well, even passing HTML through agility pack, and it just doesn't work either.
What is the proper method or field name or something to update that richtextbox?
do i need a cdata? or something? I'm very confused, and the doco on MSDN isn't that great for this method.
Pass it through an HTML encode, and it seems to work fine:
private static string SetProperHTML(string sHtml)
{
var sb = new StringBuilder();
var stringWriter = new StringWriter(sb);
string input = sHtml;
var test = new HtmlAgilityPack.HtmlDocument();
test.LoadHtml(input);
test.OptionOutputAsXml = false;
test.OptionCheckSyntax = true;
test.OptionFixNestedTags = true;
test.OptionAutoCloseOnEnd = true;
test.OptionWriteEmptyNodes = true;
test.Save(stringWriter);
Console.WriteLine(sb.ToString());
return WebUtility.HtmlEncode(sb.ToString().Replace(Environment.NewLine, ""));
}
Also want to make sure that your field descriptor is setup properly:
_batchElement.InnerXml =
string.Format(
"<Method ID='1' Cmd='New'><Field Name='Other_x0020_Items_x0020_of_x0020'>{0}</Field><Field Name='Overall_x0020_rating_x0020_of_x0'>{1}</Field><Field Name='Do_x0020_you_x0020_wish_x0020_to'>{2}</Field></Method>",
SetProperHTML(add_Report_Details.Document.Body.InnerHtml),
arrText,
addreportwish);
it's a field like any other, no special child tags needed. As long as the Sp2010 field on the form is setup for 100% full HTML, this should work. There are other HTMLEncoders out there, which may be better than the WebUtility but, for the most part, this should work, given Agility Pack is fixing most of the HTML.

Categories