473,659 Members | 2,656 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Best way to get the value of one particular node of an XML string

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.
Can anyone help?
Ideally I'd like a function (VB.NET) that takes the xml as one parameter (as
a string), and the cmd "name" as another parameter (also as a string), and
returns a string containing the value.
Thanks!
-Scott
Nov 12 '05 #1
3 1871


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(n ew
StringReader(xm lMarkup));
string value = null;
while (xmlReader.Read ()) {
if (xmlReader.Node Type == XmlNodeType.Ele ment && xmlReader.Name
== elementName) {
if (xmlReader.GetA ttribute(attrib uteName) == attributeValue) {
value = xmlReader.ReadE lementString();
break;
}
}
}
xmlReader.Close ();
return value;
}

here are two example calls:

string exampleMarkup = @"<Commands>
<cmd name=""1"">Valu e 1</cmd>
<cmd name=""2"">Valu e 2</cmd>
<cmd name=""3"">Valu e 3</cmd>
</Commands>";
string valueFound = GetValue(exampl eMarkup, "cmd", "name", "2");
Console.WriteLi ne("Found value \"{0}\".", valueFound);
valueFound = GetValue(exampl eMarkup, "cmd", "name", "5");
Console.WriteLi ne("Found value \"{0}\".", valueFound);
--

Martin Honnen --- MVP XML
http://JavaScript.FAQTs.com/
Nov 12 '05 #2
What if it were one level more complicated?

For example, given this data:

<Commands>
<cmd name="1">
<item name="result">C omplete</item>
</cmd>
<cmd name="2">
<item name="result">R eturned</item>
<item name="id">12345 </item>
</cmd>
<cmd name="3">
<item name="result">T ested</item>
</cmd>
</Commands>

I need a function that takes the following parameters:
cmd name value
item name value
For example, in one case, I want to get the data from cmd name "2", and item
"result". Another time it may be cmd name "2" and item "id".
Ideas?
Thanks!
-Scott

"Martin Honnen" <ma*******@yaho o.de> wrote in message
news:OS******** ******@TK2MSFTN GP10.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(n ew
StringReader(xm lMarkup));
string value = null;
while (xmlReader.Read ()) {
if (xmlReader.Node Type == XmlNodeType.Ele ment && xmlReader.Name ==
elementName) {
if (xmlReader.GetA ttribute(attrib uteName) == attributeValue) {
value = xmlReader.ReadE lementString();
break;
}
}
}
xmlReader.Close ();
return value;
}

here are two example calls:

string exampleMarkup = @"<Commands>
<cmd name=""1"">Valu e 1</cmd>
<cmd name=""2"">Valu e 2</cmd>
<cmd name=""3"">Valu e 3</cmd>
</Commands>";
string valueFound = GetValue(exampl eMarkup, "cmd", "name", "2");
Console.WriteLi ne("Found value \"{0}\".", valueFound);
valueFound = GetValue(exampl eMarkup, "cmd", "name", "5");
Console.WriteLi ne("Found value \"{0}\".", valueFound);
--

Martin Honnen --- MVP XML
http://JavaScript.FAQTs.com/

Nov 12 '05 #3


Scott M. Lyon wrote:
What if it were one level more complicated?

For example, given this data:

<Commands>
<cmd name="1">
<item name="result">C omplete</item>
</cmd>
<cmd name="2">
<item name="result">R eturned</item>
<item name="id">12345 </item>
</cmd>
<cmd name="3">
<item name="result">T ested</item>
</cmd>
</Commands>

I need a function that takes the following parameters:
cmd name value
item name value


Check out the XmlTextReader API then, you simply pull in nodes calling
the Read method or more specialized methods and can check the current
node type, node name as my example showed. You only have the implement
the logic then to check the attribute value of <cmd> elements and if you
find what you are looking for to implement the next lookup for the
<item> element with the proper attribute value.
<http://msdn.microsoft. com/library/default.asp?url =/library/en-us/cpref/html/frlrfSystemXmlX mlTextReaderCla ssTopic.asp>
--

Martin Honnen --- MVP XML
http://JavaScript.FAQTs.com/
Nov 12 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

136
9307
by: Matt Kruse | last post by:
http://www.JavascriptToolbox.com/bestpractices/ I started writing this up as a guide for some people who were looking for general tips on how to do things the 'right way' with Javascript. Their code was littered with document.all and eval, for example, and I wanted to create a practical list of best practices that they could easily put to use. The above URL is version 1.0 (draft) that resulted. IMO, it is not a replacement for the FAQ,...
7
3813
by: Sashi | last post by:
Two questions: (1) I can pull the text of an XML element as a string just fine using code as such: strSomeString = myXmlDoc.SelectSingleNode("/Element1/Element2/Element3", myXmlNSMgr).InnerText;
2
6800
by: Robert W. | last post by:
In a posting earlier this year I found a simple approach to convert a string to a particular Enum value. The one line solution looked like this: MyEnum ConvertedString = (MyEnum) Enum.Parse(typeof(MyEnum), MyString, true); This is fine if one wants to hardcode each and every Enum in an If-ElseIf or Select-Case construct but I'm wondering if there's a way to do it generically? I have a situation where I'm using reflection to set a...
1
1785
by: Dica | last post by:
hi all first off, i'm not trying to cross post, but couldn't find this newsgroup earlier (got here from a recommendation on microsoft.public.vb, where i originally posted this question). anyhow, i'm just getting into .Net and am trying to parse a document, but not able to read the values for the nodes consistently. anybody know what i'm doing wrong? it seems that i'm able to console.writeLine the value of the node at the beginning of...
2
1480
by: Scott M. Lyon | last post by:
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">
5
1797
by: patrin | last post by:
Hi All, given the source document: <?xml version="1.0" encoding="UTF-8"?> <root> <child> <test id="1" name="first child"/> </child> <child>
1
11780
by: =?Utf-8?B?SmVyZW15X0I=?= | last post by:
I am working on an order entry program and have a question related to deserializing nodes with nested elements. The purchase order contains multiple line items which I select using an XmlNodeList. I am trying to deserialize the nodes using a foreach as follows: foreach(XmlNode lineItem in LineItemsNodeList) An abbreviated example of the nested lineItem node looks like this:
17
1452
by: =?Utf-8?B?VGVycmFuY2U=?= | last post by:
Hello, I was wondering if someone can give me a few pointers in catching an exception correctly or at least making the code a little more elegant than what I have. I have a rss reader that I built in VB. When I read the contents from the xml file I create several labels controls that I place on the form at runtime. My problem is that some rss feeds do not have a particular node (in this case a "pubDate" for the publishing date of the feed)...
0
8427
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8332
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8746
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8525
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
6179
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5649
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4175
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4335
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1737
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.