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;
};
}
Related
I have problem parse XML in C# because XML not have root element.
How can I add root element? When try XDocument show erorrs about root element.
Maybe can use some file stream?
Example:
<data>
<datetime>29.06.2020 10:15:15</datetime>
<Lenght/>
<Width>3</Width>
<Height>2</Height>
</data>
<data>
<datetime>29.06.2020 10:15:01</datetime>
<Lenght>1</Lenght>
<Width>2</Width>
<Height>3</Height>
</data>
My code:
XmlDocument report = new XmlDocument();
report.Load(fileOfReport); //there show error about root element
XmlElement root = report.CreateElement("root");
var items = report.GetElementsByTagName("data");
for (int i = 0; i < items.Count; i++)
{
root.AppendChild(items[i]);
}
report.AppendChild(root);
report.SaveAs(fileOfReport);
You can try the following solution.
Lots of minutiae string handling, but seems to be working for your case. XmlNodeType enumerator has 18 entries total. Your XML is relatively simple, that's why the switch has just 3 node types in the code. You can use StringBuilder instead of string data type while composing a well-formed XML.
void Main()
{
const string FILENAME = #"e:\temp\NoRootFile.xml";
const string NEWFILENAME = #"e:\temp\NoRootFileFixed.xml";
string xmlString = "<root>";
XmlReaderSettings settings = new XmlReaderSettings();
settings.ConformanceLevel = ConformanceLevel.Fragment;
using (XmlReader xr = XmlReader.Create(FILENAME, settings))
{
while (xr.Read())
{
if (xr.NodeType != XmlNodeType.XmlDeclaration)
{
switch (xr.NodeType)
{
case XmlNodeType.Element:
xmlString += "<" + xr.Name + ((xr.IsEmptyElement) ? "/>" : ">");
break;
case XmlNodeType.Text:
xmlString += xr.Value;
break;
case XmlNodeType.EndElement:
xmlString += "</" + xr.Name + ">";
break;
}
}
}
}
xmlString += "</root>";
XDocument xdoc = XDocument.Parse(xmlString);
xdoc.Save(NEWFILENAME);
}
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.
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
}
}
}
I have some XML that looks like this:
<PackageConstruct900 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<ID>{5209724e-1c5a-4d84-962e-371271c3836c}</ID>
<ParentID />
<Name />
<Type>Package</Type>
<Tasks>
<anyType xsi:type="Task">
<ID>{4c97132c-ba7d-4fba-9b01-333976e9ad22}</ID>
<ParentID>{E893A7FD-2758-4315-9181-93F8728332E5}</ParentID>
<Name>ProcessAgility</Name>
<Type>Task</Type>
<StartedOn>1900-01-01T00:00:00</StartedOn>
<EndedOn>1900-01-01T00:00:00</EndedOn>
</anyType>
</Tasks>
</PackageConstruct900>
I'm trying to capture the Value of the second "Name" node ("ProcessAgility").
But (XmlReader) reader.Value returns an empty string when I arrive at this node. How do I capture the TEXT that falls betweeen <nodeName>TEXT</nodeName> ?
Here's my code so far:
XmlReader reader = XmlReader.Create(pathToFile, settings);
reader.MoveToContent();
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Text:
break;
case XmlNodeType.Element:
switch (reader.Name)
{
case "anyType":
newJob = true;
break;
case "AML":
string ss = string.Empty;
ss = reader.ReadInnerXml();
ss = System.Net.WebUtility.HtmlDecode(ss);
rs = XmlReader.Create(ss, settings);
break;
case "Name":
if (newJob && reader.HasValue)
{
jobName = reader.Value;
}
if (!string.IsNullOrWhiteSpace(jobName))
{
if (!jobsAdded.Contains(jobName))
{
jobsAdded.Add(jobName);
}
}
break;
case "Tasks":
m_ConvertingTask = true;
break;
case "TRIGGERS":
break;
}
break;
}
}
Try using XmlDocument then you can use XPath navigation like this: /PackageConstruct900/Tasks/anyType/Name
XmlDocument doc = new XmlDocument();
doc.LoadXml("<PackageConstruct900 xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\r\n <ID>{5209724e-1c5a-4d84-962e-371271c3836c}</ID>\r\n <ParentID />\r\n <Name />\r\n <Type>Package</Type>\r\n <Tasks>\r\n <anyType xsi:type=\"Task\">\r\n <ID>{4c97132c-ba7d-4fba-9b01-333976e9ad22}</ID>\r\n <ParentID>{E893A7FD-2758-4315-9181-93F8728332E5}</ParentID>\r\n <Name>ProcessAgility</Name>\r\n <Type>Task</Type>\r\n <StartedOn>1900-01-01T00:00:00</StartedOn>\r\n <EndedOn>1900-01-01T00:00:00</EndedOn>\r\n </anyType>\r\n </Tasks>\r\n</PackageConstruct900>");
XmlNode root = doc.DocumentElement;
XmlNode node = root.SelectSingleNode(
"/PackageConstruct900/Tasks/anyType/Name");
Console.WriteLine(node.InnerXml);
This will give you the first node, if you want the list then iterate it you can use:
XmlNodeList nodes = root.SelectNodes("/PackageConstruct900/Tasks");
foreach (XmlNode node in nodes)
{
var typename = node.SelectSingleNode("anyType/Name");
Console.WriteLine(typename.InnerXml);
}
A pretty simple (and very specific) System.Xml.Linq.XElement solution would be:
string processAgility = XElement.Parse(File.ReadAllText(pathToFile))
.Element("Tasks")
.Element("anyType")
.Element("Name")
.Value;
Or if you include a using System.Xml.XPath directive, you could use XPath natigation with the XPathSelectElement extension method:
string processAgility = XElement.Parse(File.ReadAllText(pathToFile))
.XPathSelectElement("Tasks/anyType/Name")
.Value;
This is the XML that i want to read.
<Server ServerName="SP-SWD-T01">
Some nodes are there
</Server>
I want to read the ServerName inside the server how can i read it.Please help.
This is the code
XmlReaderSettings readerSettings = new XmlReaderSettings();
readerSettings.IgnoreComments = false;
XmlReader xmlRdr = XmlReader.Create(strFilePath, readerSettings);
// Parse the file
while (xmlRdr.Read())
{
switch (xmlRdr.NodeType)
{
case XmlNodeType.Element:
// You may need to capture the last element to provide a context
// for any comments you come across... so copy xmlRdr.Name, etc.
break;
case XmlNodeType.Comment:
MessageBox.Show(xmlRdr.Name);
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;
}
}
Thanks
try this
String xml = #"<Server ServerName=""SP-SWD-T01"">Some nodes are there</Server>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
String servername = doc.SelectSingleNode("/Server").Attributes["ServerName"].Value;