How to turn url into XML - c#

I'm trying to use this URL...
http://www.webservicex.net/stockquote.asmx/GetQuote?Symbol=T
It acts like a XML but it isn't in the right format, I want to be able to use it to display it in XML form...
this is my code right now
protected void btnGetResult_Click(object sender, EventArgs e)
{
XPathNavigator nav;
XmlDocument myXMLDocument = new XmlDocument();
String stockQuote = "http://www.webservicex.net/stockquote.asmx/GetQuote?Symbol=T" + txtInfo.Text;
myXMLDocument.Load(stockQuote);
// Create a navigator to query with XPath.
nav = myXMLDocument.CreateNavigator();
nav.MoveToRoot();
nav.MoveToFirstChild();
do
{
//Find the first element.
if (nav.NodeType == XPathNodeType.Element)
{
//Move to the first child.
nav.MoveToFirstChild();
//Loop through all the children.
do
{
//Display the data.
txtResults.Text = txtResults.Text + nav.Name + " - " + nav.Value + Environment.NewLine;
} while (nav.MoveToNext());
}
} while (nav.MoveToNext());
}

Have a look at the source of the response you receive. The content (everything with the rootnode) is no XML. The tags are HTML entities: < and >. Loading that straight into you XmlDocument will treat all the content you are after as simple text.
The following example downloads the online resource, replaces the HTML entities with tags and reloads the XML document, which is then accessible by XPath.
string url = "http://www.webservicex.net/stockquote.asmx/GetQuote?Symbol=T";
XmlDocument doc = new XmlDocument();
doc.Load(url);
string actualXml = doc.OuterXml;
actualXml = actualXml.Replace("<", "<");
actualXml = actualXml.Replace(">", ">");
doc.LoadXml(actualXml);
I haven't considered the second part of your example source code. But I guess having a proper XML document will be the first step.

Related

How to add a new node to an existing xml? using c# [duplicate]

I have the following code:
string PathName = "C:\\Users\\TestUser\\Documents\\Project";
string FileName = "settings.xml";
XmlDocument Settings = new XmlDocument();
Settings.Load(Path.Combine(PathName, FileName));
XmlNode KnowledgeNode = Settings.SelectSingleNode("/Config/Map/Knowledge");
XmlNode UsersNode = Settings.CreateNode(XmlNodeType.Element, "Users", null);
XmlAttribute FileDirectory = Settings.CreateAttribute("FileDirectory");
FileDirectory.Value = UserSelectedFileDirectory;
UsersNode.Attributes.Append(FileDirectory);
KnowledgeNode.AppendChild(UsersNode);
Settings.Save(Path.Combine(PathName, FileName));
This results in my XML file containing <Users FileDirectory="C:\data" />
instead of <Users FileDirectory="C:\data" ></Users> as I want.
How do I create the end element? I've given it a Google and I can't find much. Any help is appreciated, thanks.
Here are three ways to force XmlDocument.Save to output a separate end tag for an empty XmlElement instead of an empty, self-closing tag.
Method 1
Insert an empty whitespace node inside the element:
UsersNode.AppendChild(Settings.CreateWhitespace(""));
Here's the output:
<Users FileDirectory="C:\data"></Users>
Method 2
Set the XmlElement.IsEmpty property of the element to false:
((XmlElement)UsersNode).IsEmpty = false;
Note that with this method, the default XML formatting settings will insert a line break between the start tag and the end tag. Here's the output:
<Users FileDirectory="C:\data">
</Users>
Method 3
Derive a custom XmlTextWriter that forwards all WriteEndElement calls to WriteFullEndElement:
public class CustomXmlTextWriter : XmlTextWriter
{
public CustomXmlTextWriter(string fileName)
: base(fileName, Encoding.UTF8)
{
this.Formatting = Formatting.Indented;
}
public override void WriteEndElement()
{
this.WriteFullEndElement();
}
}
Usage:
using (var writer = new CustomXmlTextWriter(Path.Combine(PathName, FileName)))
{
Settings.Save(writer);
}
This method might require less code overall if you have a lot of empty elements in your document.
As with Method 2, the default XML formatting settings will insert a line break between the start tag and end tag of each empty element.

update and save xml node

hello I have this xml code
<AriaGostarInformation>
<MenuInformation>
<MenuNames Name="1">
home
</MenuNames>
<MenuNames Name="2">
pages
</MenuNames>
<MenuNames Name="3">
blog
</MenuNames>
<MenuNames Name="4">
gallery
</MenuNames>
<MenuNames Name="5">
about us
</MenuNames>
<MenuNames Name="6">
contact us
</MenuNames>
<SubMenuNames parentName="1">
fgfgfgfgs
</SubMenuNames>
<SubMenuNames parentName="3">
</SubMenuNames>
</MenuInformation>
</AriaGostarInformation>
and c# code:
public void updateXmlNodeWithAttribute(string XmlNodeName, string XmlAttributeName, List<string> XmlNodeAttribute, List<string> XmlNodeValue)
{
XmlDocument xdoc = new XmlDocument();
xdoc.Load(_connection);
XmlNodeList xnode = getXmlNodeList(XmlNodeName);
for (int i = 0; i < XmlNodeAttribute.Count - 1; i++)
{
foreach (XmlNode item in xnode)
{
if (item.Attributes[XmlAttributeName].Value == XmlNodeAttribute[i].ToString())
{
item.InnerText = XmlNodeValue[i].ToString();
}
}
}
xdoc.Save(_connection);
}
The getXmlNodeList method return Specified xmlnodelist from XML file
This code does not throw an error, but DOES NOT update the XML node.
public XmlNodeList getXmlNodeList(string XmlNodeName)
{
XmlDocument doc = new XmlDocument();
doc.Load(_connection);
XmlNodeList elemList = doc.GetElementsByTagName(XmlNodeName);
return elemList;
}
Please help me where is error in my code?
I found two problems in your code.
The first error is in your for loop. With -1 the last element in the List is always not used. Or if you only have one element in your list the for loop is never executed.
The second problem is, that you load the XML file twice. First time you load it in the updateXmlNodeWithAttribute method. Second time you load it in the getXmlNodeList method.
You must know that each loaded XML Document is independent from other loaded XML Document.
So what your code does is you get a List with XML Nodes from your XML file loaded in the getXmlNodeList Method, edit one of these XML Nodes and then you try to save the XML Document loaded in the updateXmlNodeWithAttribute method where no changes were made because the two XML Documents are completely independent.
So what you have to do is use the same XmlDocument object in both methods.
See the code below.
public static void updateXmlNodeWithAttribute(string XmlNodeName, string XmlAttributeName, List<string> XmlNodeAttribute, List<string> XmlNodeValue)
{
XmlDocument xdoc = new XmlDocument();
xdoc.Load(_connection);
XmlNodeList xnode = getXmlNodeList(XmlNodeName,xdoc);
for (int i = 0; i < XmlNodeAttribute.Count; i++)
{
foreach (XmlNode item in xnode)
{
if (item.Attributes[XmlAttributeName].Value == XmlNodeAttribute[i].ToString())
{
item.InnerText = XmlNodeValue[i].ToString();
}
}
}
xdoc.Save(_connection);
}
public static XmlNodeList getXmlNodeList(string XmlNodeName, XmlDocument doc)
{
XmlNodeList elemList = doc.GetElementsByTagName(XmlNodeName);
return elemList;
}

XML selectsinglenode how i filter tag?

I'm starting to program in C # and i am beginner, so i don't have experience. I want to one day be a professional and started to develop solutions. My program save the information in xml file and then read the same information in same xml. The xml file has this format
<Dados>
<Nome>Vitor Emanuel Macedo Ferreira</Nome>
<Sexo>M</Sexo>
<Idade>22</Idade>
<Peso>86</Peso>
<Altura>1.87</Altura>
</Dados>
And in C# code my solution has:
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "XML|*.xml";
ofd.FileName = ("c:\\xml\\data.xml");
if (ofd.ShowDialog() == DialogResult.OK)
{
XmlDocument xDoc = new XmlDocument();
xDoc.Load(ofd.FileName);
xDoc.SelectSingleNode("Dados");
if (ofd.FileName == "c:\\xml\\data.xml" && xDoc.SelectSingleNode(string.Empty) == xDoc.SelectSingleNode("Dados"))
{
label8.Show();
textBox1.Hide();
textBox2.Hide();
textBox3.Hide();
radioButton1.Hide();
radioButton2.Hide();
label1.Hide();
label2.Hide();
label3.Hide();
label4.Hide();
label5.Hide();
}
else if (ofd.FileName == "c:\\xml\\data.xml" && xDoc.SelectSingleNode("") != xDoc.SelectSingleNode("Dados"))
{
MessageBox.Show("XML in incorrect path please put your xml file in c:\\xml");
}
}
How can I filter the content of the xml file, especially the tag . I need that my solution read the xml file and when he read the tag he should be able to say through Messagebox "Error tag is not equal to ", otherwise if tag equals to he must to continue
Check this:
XmlDocument doc = new XmlDocument();
doc.Load(ofd.Filename);
Now use XmlNode to traverse through nodes:
XmlNode rootNode = doc.SelectSingleNode("Dados");
Retrieve other nodes as well in this manner:
XmlNode nomeNode = rootNode.SelectSingleNode("Nome");
XmlNode saxoNode = rootNode.SelectSingleNode("Saxo");
This should give you a start.
You want to make use of XPath to navigate your XML document.
There's a guide on using it in C# here.

C# XMLdocument writing same thing over again

In my application, lots of data is generated and then written in a XML file using XmlDocument.
The mechanics works fine, but when I call the function that serializes again and again to write data in a new XML, it copies what it wrote previously to the new XML plus the new data!
I don't understand, I'm calling XmlDocument doc = new XmlDocument() at the beggining of the function that serializes...
private static Boolean SaveParsedDataAsXML(ParsedData DataParsed, String Name)
{
try
{
XmlDocument doc = new XmlDocument();
XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration, "", "");
doc.AppendChild(xmlnode);
XmlElement generalVariables = doc.CreateElement("Variables");
generalVariables.AppendChild(SerializeElement(doc, "Path", DataParsed.Path));
.
.
.
XmlElement chatMessages = doc.CreateElement("ChatMessages");
foreach (Message mess in DataParsed.ChatMessages)
{
XmlElement singleMess = doc.CreateElement("SingleMessage");
singleMess.AppendChild(SerializeElement(doc, "MessageID", mess.MessageID.ToString()));
singleMess.AppendChild(SerializeElement(doc, "MessageName", mess.MessageName));
singleMess.AppendChild(SerializeElement(doc, "MessageTime", mess.MessageTime.ToString()));
singleMess.AppendChild(SerializeElement(doc, "MessageContent", mess.MessageContent));
singleMess.AppendChild(SerializeElement(doc, "MessageTarget", mess.MessageTarget.ToString()));
chatMessages.AppendChild(singleMess);
}
generalVariables.AppendChild(chatMessages);
.
.
.
doc.AppendChild(generalVariables);
//Saving and returning true, serialization successful.
doc.Save(OutputPath + "\\" + ReplayName + ".xml");
return true;
}
catch
{
return false;
}
}
My assumption would be that you're not clearing the DataParsed.ChatMessages object before you pass it in to the function you posted.
Are you sure you're using a new DataParsed object each time? Or are you re-using the same instance and appending more messages to it?

ASP.net load XML file from URL

Trying to just simply parse an XML file;
protected void Page_Load(object sender, EventArgs e)
{
XmlDocument xdoc = new XmlDocument();//xml doc used for xml parsing
xdoc.LoadXml("http://latestpackagingnews.blogspot.com/feeds/posts/default");//loading XML in xml doc
XmlNodeList xNodelst = xdoc.DocumentElement.SelectNodes("entry");//reading node so that we can traverse thorugh the XML
foreach (XmlNode xNode in xNodelst)//traversing XML
{
litFeed.Text += "read";
}
}
But I get:
Data at the root level is invalid.
Line 1, position 1.
Do I have to do an XMLHTTP request to the file first? Or am I right to assume I can load it in from an external url?
try this :
protected void Page_Load(object sender, EventArgs e)
{
XmlDocument xdoc = new XmlDocument();//xml doc used for xml parsing
xdoc.Load(
"http://latestpackagingnews.blogspot.com/feeds/posts/default"
);//loading XML in xml doc
XmlNodeList xNodelst = xdoc.DocumentElement.SelectNodes("entry");//reading node so that we can traverse thorugh the XML
foreach (XmlNode xNode in xNodelst)//traversing XML
{
litFeed.Text += "read";
}
}
LoadXml is waiting for an xml string directly, where Load can use an uri to grab the xml data. With your code, the xml parser was actually trying to parse the adress as xml, not the content at the uri location.
[Edit] you may take a look at the builtin feed processing classes of the .Net Framework. These classes are in the System.ServiceModel.Syndication namespace. They can to the parsing job for you quite easily.

Categories