I am trying to read xml from web response and get selected nodes (i.e link) from it. This is what I have so far and its showing "System.Xml.XmlElement", as an output.
WRequest method, sends a POST request to url using web request and returns a string xml response such as:
<status> <code>201</code>
<resources_created>
<link href="####" rel="############" title="####" />
</resources_created>
<warnings> <warning>display_date is read-only</warning> </warnings>
</status>
ReadUri2 method
public static string readUri2()
{
string uri = "";
string xml = WRequest();
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml);
XmlNode elem = xmlDoc.DocumentElement.FirstChild;
uri = elem.ToString();
return uri;
}
PageLoad calls
protected void Page_Load(object sender, EventArgs e)
{
string uri = readUri2();
Label1.Text = Server.HtmlEncode(uri);
}
Any help would be very much appreciated. Many thanks.
The immediate problem (the reason you're seeing System.Xml.XmlElement
) is that you're calling ToString
on an XmlElement
, which doesn't override that method. You probably want to use the InnerXml
or OuterXml
properties instead:
XmlNode elem = xmlDoc.DocumentElement.FirstChild;
return elem.OuterXml;
That's returning the whole of the XML of the first child, which is code
. Next you'll want to change which element you're looking for, and get the right attributes.
As a side note, I'd strongly recommend using LINQ to XML instead - it's a generally nicer XML API. For example:
// TODO: Rename the `WRequest` method; that's horrible.
var document = XDocument.Parse(WRequest());
var href = document.Descendants("link").Single().Attribute("href").Value;
See more on this question at Stackoverflow