How to display hierarchical XML from a DataSet - c#

I am trying to generate a XML using [WebMethod]..
Here is my webmethod in MyMethod.asmx.cs:
[WebMethod]
public string GetTransactionList(string AccNo)
{
TransactionRepository transRep = new TransactionRepository();
IList<Transaction> listTrans = transRep.GetTransactionList(AccNo);
IList<Parameter> listPara = transRep.GetAllParameter();
DataTable tblTrans = CommonDatatableMethods.ConvertToDataTable<Transaction>(listTrans, true);
tblTrans.TableName = "transaction";
tblTrans.Columns.Remove("SequenceNo");
tblTrans.Columns.Remove("ID");
/** Note: Require insert into dataset to gain custom root name**/
DataSet dsTrans = new DataSet("Transactions");
dsTrans.Tables.Add(tblTrans);
StringWriter sw = new StringWriter();
tblTrans.WriteXml(sw);
if (listTrans.Count <= 0)
{
string emptydata = string.Empty;
emptydata = "<Transactions><transaction>No record for " + AccNo + " within " + listPara[0].ParameterYears + " years data.</transaction></Transactions>";
return emptydata;
}
else
{
/** Note: Need to remove all the schemas in meta tag**/
return sw.ToString().Replace(" xsi:type=\"xs:string\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"", "").Replace(" xml:space=\"preserve\"", "");
}
}
But when I click button invoke on my webservice,
The XML display only one line like this:
<Transactions><transaction><AccNo>ABC15279182719</AccNo><FirstName>AHMAD ALI</FirstName></transaction></Transactions>
What I want is something hierarchical like this:
<Transactions>
<transaction>
<AccNo>ABC15279182719</AccNo>
<FirstName>AHMAD ALI</FirstName>
</transaction>
</Transactions>
How do I make like that?
Thank You!

As sa_ddam213 said, your web method is working fine and returns the string value.
If you need to format the output result. open your notepad in visual studio and press ctrl+k+d for formatting.
--SJ

Related

Issues creating and writing data to a CSV file using C#

I'm using C# Code in Ranorex 5.4.2 to create a CSV file, have data gathered from an XML file and then have it write this into the CSV file. I've managed to get this process to work but I'm experiencing an issue where there are 12 blank lines created beneath the gathered data.
I have a file called CreateCSVFile which creates the CSV file and adds the headers in, the code looks like this:
writer.WriteLine("PolicyNumber,Surname,Postcode,HouseNumber,StreetName,CityName,CountyName,VehicleRegistrationPlate,VehicleMake,VehicleModel,VehicleType,DateRegistered,ABICode");
writer.WriteLine("");
writer.Flush();
writer.Close();
The next one to run is MineDataFromOutputXML. The program I am automating provides insurance quotes and an output xml file is created containing the clients details. I've set up a mining process which has a variable declared at the top which shows as:
string _PolicyHolderSurname = "";
[TestVariable("3E92E370-F960-477B-853A-0F61BEA62B7B")]
public string PolicyHolderSurname
{
get { return _PolicyHolderSurname; }
set { _PolicyHolderSurname = value; }
}
and then there is another section of code which gathers the information from the XML file:
var QuotePolicyHolderSurname = (XmlElement)xmlDoc.SelectSingleNode("//cipSurname");
string QuotePolicyHolderSurnameAsString = QuotePolicyHolderSurname.InnerText.ToString();
PolicyHolderSurname = QuotePolicyHolderSurnameAsString;
Report.Info( "Policy Holder Surname As String = " + QuotePolicyHolderSurnameAsString);
Report.Info( "Quote Policy Holder Surname = " + QuotePolicyHolderSurname.InnerText);
The final file is called SetDataSource and it puts the information into the CSV file, there is a variable declared at the top like this:
string _PolicyHolderSurname = "";
[TestVariable("222D47D2-6F66-4F05-BDAF-7D3B9D335647")]
public string PolicyHolderSurname
{
get { return _PolicyHolderSurname; }
set { _PolicyHolderSurname = value; }
}
This is then the code that adds it into the CSV file:
string Surname = PolicyHolderSurname;
Report.Info("Surname = " + Surname);
dataConn.Rows.Add(new string[] { Surname });
dataConn.Store();
There are multiple items in the Mine and SetDataSource files and the output looks like this in Notepad++:
Picture showing the CSV file after the code has been run
I believe the problem lies in the CreateCSVFile and the writer.WriteLine function. I have commented this region out but it then produces the CSV with just the headers showing.
I've asked some of the developers I work with but most don't know C# very well and no one has been able to solve this issue yet. If it makes a difference this is on Windows Server 2012r2.
Any questions about this please ask, I can provide the whole files if needed, they're just quite long and repetitive.
Thanks
Ben Jardine
I had the exact same thing to do in Ranorex. Since the question is a bit old I didn't checked your code but here is what I did and is working. I found an example (probably on stack) creating a csv file in C#, so here is my adaptation for using in Ranorex UserCodeCollection:
[UserCodeCollection]
public class UserCodeCollectionDemo
{
[UserCodeMethod]
public static void ConvertXmlToCsv()
{
System.IO.File.Delete("E:\\Ranorex_test.csv");
XDocument doc = XDocument.Load("E:\\lang.xml");
string csvOut = string.Empty;
StringBuilder sColumnString = new StringBuilder(50000);
StringBuilder sDataString = new StringBuilder(50000);
foreach (XElement node in doc.Descendants(GetServerLanguage()))
{
foreach (XElement categoryNode in node.Elements())
{
foreach (XElement innerNode in categoryNode.Elements())
{
//"{0}," give you the output in Comma seperated format.
string sNodePath = categoryNode.Name + "_" + innerNode.Name;
sColumnString.AppendFormat("{0},", sNodePath);
sDataString.AppendFormat("{0},", innerNode.Value);
}
}
}
if ((sColumnString.Length > 1) && (sDataString.Length > 1))
{
sColumnString.Remove(sColumnString.Length-1, 1);
sDataString.Remove(sDataString.Length-1, 1);
}
string[] lines = { sColumnString.ToString(), sDataString.ToString() };
System.IO.File.WriteAllLines(#"E:\Ranorex_test.csv", lines);
}
}
For your information, a simple version of my xml looks like that:
<LANGUAGE>
<ENGLISH ID="1033">
<TEXT>
<IDS_TEXT_CANCEL>Cancel</IDS_TEXT_CANCEL>
<IDS_TEXT_WARNING>Warning</IDS_TEXT_WARNING>
</TEXT>
<LOGINCLASS>
<IDS_LOGC_DLGTITLE>Log In</IDS_LOGC_DLGTITLE>
</LOGINCLASS>
</ENGLISH>
<FRENCH ID="1036">
<TEXT>
<IDS_TEXT_CANCEL>Annuler</IDS_TEXT_CANCEL>
<IDS_TEXT_WARNING>Attention</IDS_TEXT_WARNING>
</TEXT>
<LOGINCLASS>
<IDS_LOGC_DLGTITLE>Connexion</IDS_LOGC_DLGTITLE>
</LOGINCLASS>
</FRENCH>
</LANGUAGE>

Winnovative With Parameters in URL

i have a big problem and i need your help. i'm trying send to url parameters to generate the pdf file with the library winnovative. when trying the first time I have no problems and generates pdf but if I want to get the pdf again this gives me error because the parameters in url they are sent and fail to request and falls when so finally assign to generate the pdf file.
I have attached the code for review:
public override void Pagina_PrimeraCarga(object sender, EventArgs e)
{
string datosRequest = Request.QueryString["DATOS"];
char delimitadores = ';';
string[] datos = datosRequest.Split(delimitadores);
imgBanco.Attributes.Add("ImageUrl", "~/App_Themes/Imagenes/Logo.gif");
System.DateTime fecha = new System.DateTime(2014, 12, 17);
lblDia.Text = Convert.ToString(fecha.Day);
lblMes.Text = Convert.ToString(fecha.Month);
lblAno.Text = Convert.ToString(fecha.Year);
string rutEmpresa = datos[3];
int rut = Convert.ToInt32(rutEmpresa);
string rutRes = rut.ToString("N0", CultureInfo.InvariantCulture).Replace(",", ".");
rutRes = rutRes + "-" + datos[4];
lblOficina.Text = "OFICINA: " + datos[0];
lblNombreTitular.Text = "NOMBRE TITULAR: " + datos[1];
lblRut.Text = "R.U.T.: " + rutRes;
lblDireccion.Text = "DIRECCION: " + datos[2];
lblFono.Text = "FONO: " + datos[5];
}
P.D: my apologies for my bad English but my native language is Spanish
P.D.2: Thanks to everyone who could help me in this case
I think that your problem is that after postBack your query string will be empty. Try this
add hiddenfield
<asp:HiddenField runat="server" ID="hidden1" />
then in your pageLoad
if (!IsPostBack)
{
string datosRequest = Request.QueryString["DATOS"];
if(datosRequest != null)
{
//do something
hidden1.Value = datosRequest ;
}
}
else
{
datosRequest = hidden1.Value;
}
I have solved the problem. I was thinking a bit and detects when passed a second time to obtain the pdf that was creating the cookie to be passed to the other form was created and therefore did not pass the data. for this reason I had to add 2 lines but my code for closing the pdf this server delete the cookie and when consulted again remove the client:
Response.Cookies.Clear ();
myCookie.Expires = DateTime.Now.AddDays (1D);

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

Adding contents via ItemsSource to a WPF datagridview

I read an xml file like so
string appDataPath1 = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string configPath1 = appDataPath1 + "/LWRF/ReaderProfiles";
string fn = System.IO.Path.Combine(configPath1 + ComboBoxProfiles.Text);
_currentProfile.Clear();
try
{
Log("Loading profile: " + fn);
_currentProfile.ReadXml(fn);
_dgvProfile.ItemsSource = _currentProfile.DefaultView;
}
catch
{
}
What else do I need to do to make the xml file contents display in the gridview? I added this code to a ComboBox_SelectionChanged event but my datagridview is blank even after the selection changes.
Most probably you are missing a / in configPath1 :
string configPath1 = appDataPath1 + "/LWRF/ReaderProfiles/";

saving webbrowser url to xml and retriving

I am trying to save my webbrowser controler URL to a xml file but I am getting an issue with certain characters preventing the save.
When I open a simple URL like this:
www.saypeople.com
It succesfully saves, however when I want to save webpage url like this:
http://scholar.google.com.pk/scholar?as_q=filetype:pdf +transistor+ AND&num=10&btnG=Search+Scholar&as_epq=&as_oq=unknown+unclear&as_eq=&as_occt=any&as_sauthors=+ &as_publication=+ &as_ylo=&as_yhi=&as_sdt=1.&as_sdtp=on&as_sdtf=&as_sdts=5&hl=en
The save fails.
I have checked a lot things and have discovered that my code only does not save when the url contains any of the two characters &<.
Please help me out.
Here is my code...
public static DialogResult Show(string Title, String url)
{
MsgBox = new addfav();
MsgBox.textBox1.Text = Title;
MsgBox.textBox2.Text = url;
MsgBox.ShowDialog();
return result;
}
const string dataxml = "data.xml";
private void button1_Click(object sender, EventArgs e)
{
//textBox2.Text containing webpage url
//textBox1.Text containing webpage title
try
{
XmlTextReader reader = new XmlTextReader(dataxml);
XmlDocument doc = new XmlDocument();
doc.Load(reader);
reader.Close();
XmlNode currNode;
XmlDocumentFragment docFrag = doc.CreateDocumentFragment();
docFrag.InnerXml = "<fav>" + "<Title>" + textBox1.Text + "</Title>" + "<url>"+ textBox2.Text + "</url>" + "</fav>";
// insert the availability node into the document
currNode = doc.DocumentElement;
currNode.InsertAfter(docFrag, currNode.LastChild);
//save the output to a file
doc.Save(dataxml);
this.DialogResult = DialogResult.OK;
MessageBox.Show("Sucessfully Added");
}
catch (Exception ex)
{
Console.WriteLine("Exception: {0}", ex.ToString());
this.DialogResult = DialogResult.Cancel;
}
MsgBox.Close();
}
and
how can i retrive url by searching specific title in xml.
<fav>
<Title>hello</Title>
<url><![CDATA[http://scholar.google.com.pk/scholar?as_q=filetype:pdf +hello+ AND&num=10&btnG=Search+Scholar&as_epq=&as_oq=unknown+unclear&as_eq=&as_occt=any&as_sauthors=+ &as_publication=+ &as_ylo=&as_yhi=&as_sdt=1.&as_sdtp=on&as_sdtf=&as_sdts=5&hl=en]]></url>
</fav>
<fav>
<Title>toad</Title>
<url><![CDATA[http://www.sciencedaily.com/search/?keyword=toad+ AND unknown OR unclear]]></url>
</fav>
i want to search and save the url of toad title in string... please help me out...
thx
Wrap the URL in a CDATA section like:
<![CDATA[THE URL CONTENT]]>
Your problems result from the fact that you can not used & and < as XML-data, as they have special meanings in XML: & starts an XML entity, < starts an XML tag. So when you need to add & and < as values, it's easiest to used a CDATA section.
EDIT
You may try the following:
XmlDocumentFragment docFrag = doc.CreateDocumentFragment();
docFrag.InnerXml = "<fav>";
docFrag.InnerXml += String.Format("<Title>{0}</Title>", textBox1.Text);
docFrag.InnerXml += String.Format("<Url><![CDATA[{0}]]></Url>", textBox2.Text);
docFrag.InnerXml += "</fav>";
You could use HttpUtility.HtmlEncode(url).
Your problem is here:
docFrag.InnerXml = "<fav>" + "<Title>" + textBox1.Text + "</Title>"
+ "<url>"+ textBox2.Text + "</url>" + "</fav>";
<, > and & that caused you problems are markup in XML. InnerXML does not escape markup and those characters get written as they are which would result in an invalid XML fragment. For adding the URL, use InnerText instead. It escapes those characters.
To navigate through an XML file, you have to use a navigator as shown here.
XPathDocument xpathDoc = new XPathDocument([location of the file]);
XPathNavigator Navigator = xpathDoc.CreateNavigator();
String url_nav = "fav/url/text()";
XPathNodeIterator url_iterator = Navigator.Select(url_nav);
String URL_value = url_iterator.Current.Value;
url_iterator.MoveNext();
If the file is too heavily nested, go for XML serialization.

Categories