Skip to content

Instantly share code, notes, and snippets.

@kristopherjohnson
Created September 12, 2012 14:34
Show Gist options
  • Save kristopherjohnson/3707029 to your computer and use it in GitHub Desktop.
Save kristopherjohnson/3707029 to your computer and use it in GitHub Desktop.
Extract value of an XML element from a document
/// <summary>
/// Extract an element value from an XML document
/// </summary>
/// <param name="xmlDocumentString">XML document string</param>
/// <param name="xmlns">XML namespace</param>
/// <param name="elementName">name of element whose value is to be returned</param>
/// <returns>System.String</returns>
/// <exception cref="System.Exception">thrown on failure</exception>
public static string GetXmlElementValue(string xmlDocumentString, string xmlns, string elementName)
{
var xdoc = XDocument.Parse(xmlDocumentString);
XNamespace xns = xmlns;
var element = xdoc.Element(xns + elementName);
return element.Value;
}
@kristopherjohnson
Copy link
Author

Example: Say you have this XML:

<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://example.com/webservices/">This is a string value</string>

You can call this:

var result = GetXmlElementValue(xml, "http://example.com/webservices", "string");

to get "This is a string value".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment