Is there an easier way to get the InnerText
from just one node in an xml
?
At the moment I'm using following code to get the value:
var xml = new XmlDocument();
xml.LoadXml(callback); //callback
string txt = xml.FirstChild.FirstChild.FirstChild.LastChild.InnerText;
I wonder if there is any way to get the value without loading the whole XmlDocument
. I just need to acces this one node and value.
Thanks in advance!
Sample XML: (the TRACK
node appears up to 80 times, here 13 times)
<RESPONSES>
<RESPONSE STATUS="OK">
<ALBUM>
<ID>some_long_id_123456789123456789</ID>
<ARTIST>some_artist</ARTIST>
<TITLE>some_album</TITLE>
<PKG_LANG>ENG</PKG_LANG>
<DATE>1234</DATE>
<GENRE NUM="123456" ID="654321">some_string</GENRE>
<TRACK_COUNT>13</TRACK_COUNT>
<TRACK>
<TRACK_NUM>1</TRACK_NUM>
<ID>some_id_123456789</ID>
<TITLE>some_title</TITLE>
</TRACK>
...
<TRACK>
<TRACK_NUM>13</TRACK_NUM>
<ID>some_id_123456789_13</ID>
<TITLE>some_title_13</TITLE>
</TRACK>
<URL TYPE="IMAGE" SIZE="MEDIUM" WIDTH="123456" HEIGHT="123456">the_url_i_wanna_access</URL>
</ALBUM>
</RESPONSE>
</RESPONSES>
A solution using LINQ to XML could be as simple as this:
var doc = XDocument.Parse(xml);
var url = (string)doc.Descendants("URL").Single();
This is a little more readable than the XmlDocument
API code you have already.
If you're concerned about performance (I'm not sure this XML is big enough to warrant this), you could use XmlReader
directly to avoid loading all the XML into the DOM just to read one piece of text:
string url;
using (var sr = new StringReader(xml))
using (var reader = XmlReader.Create(sr))
{
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element && reader.Name == "URL")
{
url = reader.ReadElementString();
break;
}
}
}