Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Reading XML with XMLReader

Status
Not open for further replies.

divinyl

IS-IT--Management
Nov 2, 2001
163
GB
Hi all,

I'm a dev newbie and need some assistance with something i'm working on. I need to read through an XML file and output the values of only certain elements. Say my xml file looks something like this:

<element id="1">
<text> Blah blah blah </text>
</element>
<element id="2">
<provide name="Access">
<defaulttext> Blah-di-blah </defaulttext>
</element>

So basically i will have a form where users can pick an a number, and this will be passed as a paramter into a function that reads through the xml file - so if you picked 1, then it will look for element id = 1, and then output the contents of the <text> tag. However, in some elements (as in element 2) it would need to output the contents of the <defaulttext> tag. So it will only ever need to output the <text> and <defaulttext> element values. So, based on the number that gets passed through in the function, my code needs to be able to find the correct element and output either <text> or <defaulttext> values, which may or may not be the next node after element (cannot rely on position as position of these elements may differ from node to node).

Can anyone point me in the right direction!? I've started off with something like this but cannot think how to carry on as i always get returned with the wrong stuff....

Code:
public string GetQuery(string commandID)

{

string QueryText = "";

string commandFile = "Commands.xml";

XmlTextReader trC = new XmlTextReader(commandFile); 


while (trC.Read())

{

if(trC.GetAttribute("id") == commandID)

{ ..........

Can anyone help?

Thanks
Divinyl
 
The easiest way to do what you want is to load the xml file into an XmlDocument and run an XPath query as follows:
XmlDocument xdoc = new XmlDocument();
xdoc.Load("Commands.xml");

XmlElement root = doc.DocumentElement;
XmlElement elem = root.SelectSingleNode("element[id='1']");
string Text = elem.SelectSingleNode("text").InnerText;
string DefaultText =
elem.SelectSingleNode("defaultext").InnerText;
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top