"result". Another time it may be cmd name "2" and item "id".
"Martin Honnen" <mahotrash@yahoo.de> wrote in message
news:OSrxXzPQFHA.1472@TK2MSFTNGP10.phx.gbl...
>
>
> Scott M. Lyon wrote:
>
>> I'm trying to figure out the best way (considering there could be
>> instances where I get a lot of data in this XML, and I want to minimize
>> any slowdowns) to extract the value of one particular node from an XML
>> string (not saved as a file, but passed as a string from another module).
>>
>>
>> For example, let's assume I get back XML in a string that looks like
>> this:
>>
>> <Commands>
>> <cmd name="1">Value 1</cmd>
>> <cmd name="2">Value 2</cmd>
>> <cmd name="3">Value 3</cmd>
>> </Commands>
>>
>>
>> I need an efficient way that I can (for example) return the value from
>> the cmd tag with name attribute "2" (so for this example, to return
>> "Value 2").
>>
>>
>> What is going to be the best way to do this? It was suggested (here) that
>> I use the XmlTextReader, but I'm not totally sure how that would work.
>
> Here is a C# method:
>
> public static string GetValue (string xmlMarkup, string elementName,
> string attributeName, string attributeValue) {
> XmlTextReader xmlReader = new XmlTextReader(new
> StringReader(xmlMarkup));
> string value = null;
> while (xmlReader.Read()) {
> if (xmlReader.NodeType == XmlNodeType.Element && xmlReader.Name ==
> elementName) {
> if (xmlReader.GetAttribute(attributeName) == attributeValue) {
> value = xmlReader.ReadElementString();
> break;
> }
> }
> }
> xmlReader.Close();
> return value;
> }
>
> here are two example calls:
>
> string exampleMarkup = @"<Commands>
> <cmd name=""1"">Value 1</cmd>
> <cmd name=""2"">Value 2</cmd>
> <cmd name=""3"">Value 3</cmd>
> </Commands>";
> string valueFound = GetValue(exampleMarkup, "cmd", "name", "2");
> Console.WriteLine("Found value \"{0}\".", valueFound);
> valueFound = GetValue(exampleMarkup, "cmd", "name", "5");
> Console.WriteLine("Found value \"{0}\".", valueFound);
>
>
> --
>
> Martin Honnen --- MVP XML
>
http://JavaScript.FAQTs.com/