ASP.net load XML file from URL - c#

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.

Related

How to update attribute of xml based on textbox value in C#

I will appreciate your help with this one.
I've written a code to enable me to modify the attribute of an xml element based on the value in the textbox.
Everything seems to work when debugged, but upto the last code, as the xml file deos not get updated. What am I doing wrong?
private void btnUpdate_Click(object sender, EventArgs e)
{
XmlDocument doc = new XmlDocument();
doc.PreserveWhitespace = true;
doc.Load("Info.xml");
XmlNamespaceManager ns = new XmlNamespaceManager(doc.NameTable);
ns.AddNamespace("root", doc.DocumentElement.NamespaceURI);
XmlNode Body = doc.SelectSingleNode("//root:Body", ns);
ns.AddNamespace("child", Body.FirstChild.NextSibling.NamespaceURI);
XmlNode nodeIr = doc.SelectSingleNode("//child:Name", ns);
nodeIr.InnerText = txtBox1.Text;
doc.Save("Info.xml");
}
I believe the last line needs to be modified.
Thank you

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;
}

Method is executed but not has effect

I'm creating a class for manipulate XML, I created overload of my method RemoveNode
public partial class HWXml
{
public string XmlFile;
private XmlDocument XmlDoc = new XmlDocument();
public HWXml(string XmlFile)
{
this.XmlFile = XmlFile;
}
public XmlNode SelectSingleNode(string NodePath)
{
XmlDoc.Load(XmlFile);
return XmlDoc.SelectSingleNode(NodePath);
}
public void RemoveNode(XmlNode removeChild)
{
XmlDoc.Load(XmlFile);
removeChild.ParentNode.RemoveChild(removeChild);
XmlDoc.Save(XmlFile);
}
public void RemoveNode(string RemoveChild)
{
XmlDoc.Load(XmlFile);
XmlNode removeChild = XmlDoc.SelectSingleNode(RemoveChild);
removeChild.ParentNode.RemoveChild(removeChild);
XmlDoc.Save(XmlFile);
}
}
When I try remove node using string parameter, it works
private void RemoveXML_Click(object sender, RoutedEventArgs e)
{
MyXmlClass myXmlClass = new MyXmlClass(XmlFile);
myXmlClass.RemoveNode("root/Content");
}
But when I try remove node using XmlNode parameters, it will compile, execute, no error message, but no effect, it no remove nothing in the XML file.
private void RemoveXML_Click(object sender, RoutedEventArgs e)
{
MyXmlClass myXmlClass = new MyXmlClass(XmlFile);
XmlNode node = myXmlClass.SelectSingleNode("root/Conteudo");
myXmlClass.RemoveNode(node);
}
What is problem?
XmlNode parameter is definitely not part of XmlDoc which you are loading inside this method (because you have this node before document is loaded). Thus manipulations on this node do not affect document which node does not belong to.
In second case you are selecting node of document which was loaded. This node belongs to xml tree which was just loaded into XmlDoc, thus removing node affects document.
What you should understand is how XmlDocument (same for XDocument) is loaded:
If it has some nodes (previously loaded) then all nodes are removed
XmlReader created
This reader reads input stream node by node
For each found node, new instance of appropriate class is created and added to document (e.g. if reader has read some element, then new XmlElement is created and added to current element of document)
So, you end up with graph of completely new objects which have no relation to objects which was created during previous load of xml. After loading xml, instance of XmlDocument stays same, but it has completely new objects inside.

How to turn url into XML

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.

How to append ChildNodes of a xml documents into root of another (web services)?

I've created a [WebMethod] on ASP.NET Web Service which reads XML documents from different web services (ASP.NET and PHP services).
Once the documents are read, they are merged into a XML and returned.
The method can successfully read XML documents from each web service but when I try to append second XML into first one, I get ArgumentException and a message like this The node to be inserted is from a different document context. I can't find a problem, can it be something to do with the source of document? but then both document are exactly same (have same elements).
Why ArgumentException? What am I missing?
[WebMethod]
public XmlDocument getRestaurants(String search_keywords)
{
XmlDocument xmlDom1 = new XmlDocument();
xmlDom1 = getRestaurantFromAspNetWS(search_keywords);
XmlTextReader myXmlTextReader =
new XmlTextReader
("http://some-iss.green.com/username/search.php?s=" + search_keywords);
XmlDocument xmlDom2 = new XmlDocument();
xmlDom2.Load(myXmlTextReader);
foreach (XmlElement xmlNode in xmlDom2.DocumentElement.ChildNodes)
{
//trying to append childNodes of xmlDom2 into xmlDom1
//and this is where i get ArgumentException
xmlDom1.DocumentElement.AppendChild(xmlNode);
}
return xmlDom1;
}
You need to import the node with importNode()
something like this:
xmlDom1.DocumentElement.importNode(xmlNode, true);
Can you write it like this?
public XElement getRestaurants(String search_keywords)
{
XElement result = getRestaurantFromAspNetWS(search_keywords);
XmlTextReader myXmlTextReader = new XmlTextReader
("http://some-iss.green.com/username/search.php?s=" + search_keywords);
XElement reader = XElement.Load(myXmlTextReader);
foreach (XElement child in reader.Elements())
result.Add(child);
return result;
}
The real trick is getting your custom getRestaurantFromAspNetWS function to return a XElement instead of a XmlDocument, as you didn't provide us with that function, I can't help you there.

Categories