How can I get a list of items straight from the xml file that is on the host?
More precisely, I want to This xml file http://gamerpro.webd.pl/data/modlist.xml I pulled out a list of items and listened to the code
If (! File.Exists ("received list of items"))
{
Await client.DownloadFileTaskAsync (new Uri (url + "received item list"), dir + "received item list");
}
using System;
using System.Xml;
namespace ReadXMLfromURL
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1
{
static void Main(string[] args)
{
String URLString = "http://localhost/books.xml";
XmlTextReader reader = new XmlTextReader (URLString);
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element: // The node is an element.
Console.Write("<" + reader.Name);
while (reader.MoveToNextAttribute()) // Read the attributes.
Console.Write(" " + reader.Name + "='" + reader.Value + "'");
Console.Write(">");
Console.WriteLine(">");
break;
case XmlNodeType.Text: //Display the text in each element.
Console.WriteLine (reader.Value);
break;
case XmlNodeType. EndElement: //Display the end of the element.
Console.Write("</" + reader.Name);
Console.WriteLine(">");
break;
}
}
}
}
}
You could do something like this
// Make your request
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestURL);
request.Headers.Add("Accept", "application/xml");
HttpResponseMessage response = client.SendAsync(request).Result;
// Parse your response
if (response.IsSuccessStatusCode)
{
using (Stream httpResponseStream = response.Content.ReadAsStreamAsync().Result)
{
XDocument responseXML = XDocument.Load(httpResponseStream);
// My Chosen element is the element you're looking for
IEnumerable<XElement> myElements = responseXML.Root.Elements("MyChosenElement");
foreach (XElement myEl in myElements)
{
// Access each element like this myEl.Child
// Do what you'd like with it
}
}
}
Related
I am trying to retrieve all elements from an XML file, but I just can reach one, is there any way I can retrieve all?
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
using (XmlReader reader = XmlReader.Create(new StreamReader(objResponse.GetResponseStream())))
{
while (reader.Read())
{
#region Get Credit Score
//if (reader.ReadToDescendant("results"))
if (reader.ReadToDescendant("ssnMatchIndicator"))
{
string ssnMatchIndicator = reader.Value;
}
if (reader.ReadToDescendant("fileHitIndicator"))
{
reader.Read();//this moves reader to next node which is text
result = reader.Value; //this might give value than
Res.Response = true;
Res.SocialSecurityScore = result.ToString();
//break;
}
else
{
Res.Response = false;
Res.SocialSecurityScore = "Your credit score might not be available. Please contact support";
}
#endregion
#region Get fileHitIndicator
if (reader.ReadToDescendant("fileHitIndicator"))
{
reader.Read();
Res.fileHitIndicator = reader.Value;
//break;
}
#endregion
}
}
Can somebody help me out with this issue?
I am also using objResponse.GetResponseStream() because the XML comes from a response from server.
Thanks a lot in advance.
Try this :
XmlDataDocument xmldoc = new XmlDataDocument();
XmlNodeList xmlnode ;
int i = 0;
string str = null;
FileStream fs = new FileStream("product.xml", FileMode.Open, FileAccess.Read);
xmldoc.Load(fs);
xmlnode = xmldoc.GetElementsByTagName("Product");
for (i = 0; i <= xmlnode.Count - 1; i++)
{
xmlnode[i].ChildNodes.Item(0).InnerText.Trim();
str = xmlnode[i].ChildNodes.Item(0).InnerText.Trim() + " " + xmlnode[i].ChildNodes.Item(1).InnerText.Trim() + " " + xmlnode[i].ChildNodes.Item(2).InnerText.Trim();
MessageBox.Show (str);
}
I don't know why what you're doing is not working, but I wouldn't use that method. I've found the following to work well. Whether you're getting the xml from a stream, just put it into a string and bang...
StreamReader reader = new StreamReader(sourcepath);
string xml = reader.ReadToEnd();
reader.Close();
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
XmlNodeList list = doc.GetElementsByTagName("*");
foreach (XmlNode nd in list)
{
switch (nd.Name)
{
case "ContactID":
var ContactIdent = nd.InnerText;
break;
case "ContactName":
var ContactName = nd.InnerText;
break;
}
}
To capture what is between the Xml tags, if there are no child Xml tags, use the InnerText property, e.g. XmlNode.InnerText. To capture what is between the quotes in the nodes' attributes, use XmlAttribute.Value.
As for iterating through the attributes, if one of your nodes has attributes, such as the elements "Name", "SpectralType" and "Orbit" in the Xml here:
<System>
<Star Name="Epsilon Eridani" SpectralType="K2v">
<Planets>
<Planet Orbit="1">Bill</Planet>
<Planet Orbit="2">Moira</Planet>
</Planets>
</Star>
</System>
Detect them using the Attributes property, and iterate through them as shown:
if (nd.Attributes.Count > 0)
{
XmlAttributeCollection coll = nd.Attributes;
foreach (XmlAttribute cn in coll)
{
switch (cn.Name)
{
case "Name":
thisStar.Name = cn.Value;
break;
case "SpectralType":
thisStar.SpectralClass = cn.Value;
break;
}
}
}
You might find some more useful information HERE.
Below is a sample of the type of XML file I am trying to handle. If I have only one part along with an accompanying number/character I can process the data extraction without the necessity of the 'if (!reader.EOF)' control structure. However when I try to include this structure so that I can loop back to checking for another part, number, and character group, it deadlocks.
Any advice as to how to do this properly? This was the most efficient idea that popped into my head. I am new to reading data from XMLs.
Sample Xml:
<?xml version="1.0" encoding="UTF-8"?>
<note>
<part>100B</part>
<number>45</number>
<character>a</character>
<part>100C</part>
<number>55</number>
<character>b</character>
</note>
Code:
String part = "part";
String number = "number";
String character = "character";
String appendString = "";
StringBuilder sb = new StringBuilder();
try
{
XmlTextReader reader = new XmlTextReader("myPath");
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element: // The node is an element.
myLabel:
if (reader.Name == part)
{
part = reader.ReadInnerXml();
}
if (reader.Name == number)
{
number = reader.ReadInnerXml();
number = double.Parse(number).ToString("F2"); //format num
}
if (reader.Name == character)
{
character = reader.ReadInnerXml();
}
//new string
appendString = ("Part: " + part + "\nNumber: " + number +
"\nCharacter: " + character + "\n");
//concatenate
sb.AppendLine(appendString);
if (reader.EOF != true)
{
Debug.Log("!eof");
part = "part";
number = "number";
character = "character";
goto myLabel;
}
//print fully concatenated result
sb.ToString();
//reset string builder
sb.Length = 0;
break;
}
}
}
catch (XmlException e)
{
// Write error.
Debug.Log(e.Message);
}
catch (FileNotFoundException e)
{
// Write error.
Debug.Log(e);
}
catch(ArgumentException e)
{
// Write error.
Debug.Log(e);
}
XmlReader class has many useful methods. Use it.
See this:
var sb = new StringBuilder();
using (var reader = XmlReader.Create("test.xml"))
{
while (reader.ReadToFollowing("part"))
{
var part = reader.ReadElementContentAsString();
sb.Append("Part: ").AppendLine(part);
reader.ReadToFollowing("number");
var number = reader.ReadElementContentAsDouble();
sb.Append("Number: ").Append(number).AppendLine();
reader.ReadToFollowing("character");
var character = reader.ReadElementContentAsString();
sb.Append("Character: ").AppendLine(character);
}
}
Console.WriteLine(sb);
Alexander's answer is fine, I just want to add sample using XDocument, according comments of Jon Skeet:
var sb = new StringBuilder();
var note = XDocument.Load("test.xml").Root.Descendants();
foreach (var el in note)
{
sb.Append(el.Name).Append(": ").AppendLine(el.Value);
}
Console.WriteLine(sb);
please view the code provided by Microsoft below:
using System;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace Microsoft.Translator.Samples
{
class TranslateArraySample
{
public static async Task Run(string authToken)
{
var from = "en";
var to = "es";
var translateArraySourceTexts = new []
{
"The answer lies in machine translation.",
"the best machine translation technology cannot always provide translations tailored to a site or users like a human ",
"Simply copy and paste a code snippet anywhere "
};
var uri = "https://api.microsofttranslator.com/v2/Http.svc/TranslateArray";
var body = "<TranslateArrayRequest>" +
"<AppId />" +
"<From>{0}</From>" +
"<Options>" +
" <Category xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\" />" +
"<ContentType xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\">{1}</ContentType>" +
"<ReservedFlags xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\" />" +
"<State xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\" />" +
"<Uri xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\" />" +
"<User xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\" />" +
"</Options>" +
"<Texts>" +
"<string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/Arrays\">{2}</string>" +
"<string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/Arrays\">{3}</string>" +
"<string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/Arrays\">{4}</string>" +
"</Texts>" +
"<To>{5}</To>" +
"</TranslateArrayRequest>";
string requestBody = string.Format(body, from, "text/plain", translateArraySourceTexts[0], translateArraySourceTexts[1], translateArraySourceTexts[2], to);
using (var client = new HttpClient())
using (var request = new HttpRequestMessage())
{
request.Method = HttpMethod.Post;
request.RequestUri = new Uri(uri);
request.Content = new StringContent(requestBody, Encoding.UTF8, "text/xml");
request.Headers.Add("Authorization", authToken);
var response = await client.SendAsync(request);
var responseBody = await response.Content.ReadAsStringAsync();
switch (response.StatusCode)
{
case HttpStatusCode.OK:
Console.WriteLine("Request status is OK. Result of translate array method is:");
var doc = XDocument.Parse(responseBody);
var ns = XNamespace.Get("http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2");
var sourceTextCounter = 0;
foreach (XElement xe in doc.Descendants(ns + "TranslateArrayResponse"))
{
foreach (var node in xe.Elements(ns + "TranslatedText"))
{
**Console.WriteLine("\n\nSource text: {0}\nTranslated Text: {1}", translateArraySourceTexts[sourceTextCounter], node.Value);**
}
sourceTextCounter++;
}
break;
default:
Console.WriteLine("Request status code is: {0}.", response.StatusCode);
Console.WriteLine("Request error message: {0}.", responseBody);
break;
}
}
}
}
}
Please look at the ** line, node.value is the result I want. According to the code, we will have 3 sentences translated from the string array above. However, I want it to display in a textbox. let say I have a textbox with ID = textbox.
I have tried using this :
foreach (var node in xe.Elements(ns + "TranslatedText"))
{
textbox.Text=node.value;
}
sourceTextCounter++;
However, the result only for the last sentence.
Please share your thought how to do it!
Try this:
foreach (var node in xe.Elements(ns + "TranslatedText"))
{
textbox.Text += node.value + " ";
}
Because you're always overwriting .Text you need to concatenate with something like:
textbox.Text += node.value + Environment.NewLine;
This would add your node.value and a newline character for each node found.
EDIT: Also want to state that Environment.NewLine is ignored if the Multiline property of the textbox is false.
I'm having program like below. The concept is Read XML value from URL, but my program read the xml structure only, not the code datas. Like <Billing Address></Billing Address>... etc only. But the original XML value is <Billing Address>Strre1</Billing Address>. The Program does not read the inside value.
public static void zohoCRMReadAccounts()
{
var val = auth();
var val1= val[0];
var val2= val[1];
String xmlURL = "URL";
XmlTextReader xmlReader = new XmlTextReader(xmlURL);
while (xmlReader.Read())
{
switch (xmlReader.NodeType)
{
case XmlNodeType.Element: // The node is an element.
Console.Write("<" + xmlReader.Name);
// Read the attributes:
while (xmlReader.MoveToNextAttribute())
Console.Write(" " + xmlReader.Name + "=’"
+ xmlReader.Value + "’");
Console.WriteLine(">");
break;
case XmlNodeType.Text: //Display the text in each element.
Console.WriteLine(xmlReader.Value);
break;
case XmlNodeType.EndElement: //Display the end of the element.
Console.Write("</" + xmlReader.Name);
Console.WriteLine(">");
break;
}
}
Console.WriteLine("Press any key to continue…");
Console.ReadLine(); //Pause
}
Please help me to fix
XML Elements cannot have spaces in their names. Try to remove them first
First download the XML. Then Use like,
try {
//read xml
XmlDocument xdoc = new XmlDocument();
xdoc.Load("XMLFilePath");
XmlNodeList nodes = xdoc.SelectNodes(#"rss/channel/item");
foreach (XmlNode node in nodes)
{
XmlNode titleNode = node.SelectSingleNode("title");
string title = titleNode == null ? string.Empty : titleNode.InnerText;
};
}
I'm using authorize.net AIM, the sample code they provide prints an ordered list of the response values. Rather than print out an ordered list to the screen where the customer would see all this information, how do I set up a switch to access certain indexs of the array and do something based on the text returned for the particular array index?
String post_response;
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
using (StreamReader responseStream = new StreamReader(objResponse.GetResponseStream()))
{
post_response = responseStream.ReadToEnd();
responseStream.Close();
}
// the response string is broken into an array
// The split character specified here must match the delimiting character specified above
Array response_array = post_response.Split('|');
// the results are output to the screen in the form of an html numbered list.
resultSpan.InnerHtml += "<OL> \n";
foreach (string value in response_array)
{
resultSpan.InnerHtml += "<LI>" + value + " </LI> \n";
}
resultSpan.InnerHtml += "</OL> \n";
Change the type of response_array to string[]:
string[] response_array = post_response.Split('|');
In C# you can switch on a string:
switch (response_array[0])
{
case "foo":
// do something...
break;
case "bar":
// do something else...
break;
default:
// Error?
break;
}