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

Home Posts Topics Members FAQ

XPath Problems.. need help!

Hi,

I read from this tutorial at codeproject

Question A:

http://www.codeproject.com/csharp/GsXPathTutorial.asp

regarding xpath.. but i try to apply in my situation, and can't get it work...

just say this is my xml file:

Device.xml
=========
<?xml version="1.0" encoding="utf-8"?>
<DeviceList xmlns="http://tempuri.org/Device.xsd">
<!-- Device 1 -->
<Device id="1">
<Connection>
<Type>Titan12 3</Type>
<Open />
<ConfigCard>
<Name>Titan Suprema</Name>
<Length>13</Length>
</ConfigCard>
</Connection>
</Device>
<Device id="2">
<Connection>
<Type>BBB Hardware</Type>
<Open />
<ConfigCard>
<Name>BBB DH</Name>
<Length>6</Length>
</ConfigCard>
</Connection>
</Device>
</DeviceList>

In my C# code,

string devicePath = Application.Sta rtupPath + @"\device.xm l";
// open XmlTextReader
....
int nMaxId = 0;

// get maximum devices within XML script
while(xmlDevice .Read())
{
if (xmlDevice.IsSt artElement() && xmlDevice.Name == "Device")
{
int nId = Int32.Parse(xml Device.GetAttri bute("id"));

if (nMaxId < nId)
nMaxId = nId;
}
}
}

// Execute XPath here
XPathDocument xdoc = new XPathDocument(d evicePath);
XPathNavigator nav = xdoc.CreateNavi gator();

// loop into 2 possible devices and extract particular information
for (int i = 1; i < nMaxId + 1; i++)
{
XPathNodeIterat or nodeItor = nav.Select(
"DeviceList/Device[@id='" + i + "']/Connection");
nodeItor.MoveNe xt();

TraverseChildre n(nodeItor);
}
....

// from the article
private void TraverseChildre n(XPathNodeIter ator nodeItor)
{
XPathNodeIterat or igor = nodeItor.Clone( );
igor.Current.Mo veToFirstChild( );
bool more = false;
do
{
PrintNode(igor. Current);
more = igor.Current.Mo veToNext();
}while(more);
}

private void PrintNode(XPath Navigator nav)
{
MessageBox.Show ("Value: " + nav.Value +
" Type : " + nav.NodeType.To String());
}

From this solution:

i get this instead:

MessageBox1 - Value: Titan123 Titan Suprema 13BBB Hardware BBB DH 6
MessageBox2 - Value: Titan123 Titan Suprema 13BBB Hardware BBB DH 6
(repeat the same message - why?)

Any help please?

I want to get the Output of this:

MessageBox1 - Value: Titan123 Titan Suprema 13
MessageBox2 - Value: BBB Hardware BBB H 6

Question B:

By the way how can i get the value of individual Type example,

showing the output here:

Type - Titan123
Name - Titan Suprema
Length - 13

i always only manage to get the type which is "Name" and the whole message
"Titan123 Titan Suprema 13" instead separate data.

Any help please? Thanks.
--
Regards,
Chua Wen Ching
Visit us at http://www.necoders.com
Nov 16 '05 #1
5 2155
Chua Wen Ching,

This seems a little overkill for what you are trying to do...

I wrote a short, but complete application that does more what I think you
want:

using System;
using System.Xml;
using System.Xml.XPat h;

namespace XmlXpathParser
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{

// load the xml into the dom
XmlDocument myDoc = new XmlDocument();
myDoc.Load ( @"XmlFile1.x ml" );

// select all deviceID nodes
XmlNodeList nodes = myDoc.SelectNod es ( "DeviceList/Device" );

// display details on each
foreach ( XmlNode deviceNode in nodes )
{
DisplayDeviceNo de ( deviceNode );
}

// wait for user response before closing
Console.WriteLi ne ( "----- press any key" );
Console.Read();
}

static void DisplayDeviceNo de ( XmlNode deviceNode )
{
string type = deviceNode.Sele ctSingleNode (
"Connection/Type" ).InnerText;
string name = deviceNode.Sele ctSingleNode (
"Connection/ConfigCard/Name" ).InnerText;
string length = deviceNode.Sele ctSingleNode (
"Connection/ConfigCard/Length").InnerT ext;

Console.WriteLi ne ( "type = {0}, name = {1}, length = {2}",
type, name, length );
}
}
}

All you need to add is some error checking for if nodes don't exist, and
exception handling for catching problems if data is corrupted.
Beware the hard coded string for the xml file... All I did was cut and paste
your xml into "XmlFile1.x ml".

HTH.

Dan.
Nov 16 '05 #2
Hi Dan Bass,

Thanks alot. It reallys helps me. But i do notice that it seems to process
a lot unlike xpath, well it is fast.. but i can't get what i want earlier (in
my previous email).

Can i do with xpath? Any tips? i heard xpath is much faster.

Cheers. Hooray :)

"Dan Bass" wrote:
Chua Wen Ching,

This seems a little overkill for what you are trying to do...

I wrote a short, but complete application that does more what I think you
want:

using System;
using System.Xml;
using System.Xml.XPat h;

namespace XmlXpathParser
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{

// load the xml into the dom
XmlDocument myDoc = new XmlDocument();
myDoc.Load ( @"XmlFile1.x ml" );

// select all deviceID nodes
XmlNodeList nodes = myDoc.SelectNod es ( "DeviceList/Device" );

// display details on each
foreach ( XmlNode deviceNode in nodes )
{
DisplayDeviceNo de ( deviceNode );
}

// wait for user response before closing
Console.WriteLi ne ( "----- press any key" );
Console.Read();
}

static void DisplayDeviceNo de ( XmlNode deviceNode )
{
string type = deviceNode.Sele ctSingleNode (
"Connection/Type" ).InnerText;
string name = deviceNode.Sele ctSingleNode (
"Connection/ConfigCard/Name" ).InnerText;
string length = deviceNode.Sele ctSingleNode (
"Connection/ConfigCard/Length").InnerT ext;

Console.WriteLi ne ( "type = {0}, name = {1}, length = {2}",
type, name, length );
}
}
}

All you need to add is some error checking for if nodes don't exist, and
exception handling for catching problems if data is corrupted.
Beware the hard coded string for the xml file... All I did was cut and paste
your xml into "XmlFile1.x ml".

HTH.

Dan.

Nov 16 '05 #3
Hi Dan,

2 more things to add on.

exception handling for catching problems if data is corrupted
--> Why do i need to catch problems if data is corrupted? Any examples? Coz
i will be writing the script in xml manually, and process it in C#.

Beware the hard coded string for the xml file
--> I don't get your meaning here. Hard coded string ???

Cheers.

"Dan Bass" wrote:
Chua Wen Ching,

This seems a little overkill for what you are trying to do...

I wrote a short, but complete application that does more what I think you
want:

using System;
using System.Xml;
using System.Xml.XPat h;

namespace XmlXpathParser
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{

// load the xml into the dom
XmlDocument myDoc = new XmlDocument();
myDoc.Load ( @"XmlFile1.x ml" );

// select all deviceID nodes
XmlNodeList nodes = myDoc.SelectNod es ( "DeviceList/Device" );

// display details on each
foreach ( XmlNode deviceNode in nodes )
{
DisplayDeviceNo de ( deviceNode );
}

// wait for user response before closing
Console.WriteLi ne ( "----- press any key" );
Console.Read();
}

static void DisplayDeviceNo de ( XmlNode deviceNode )
{
string type = deviceNode.Sele ctSingleNode (
"Connection/Type" ).InnerText;
string name = deviceNode.Sele ctSingleNode (
"Connection/ConfigCard/Name" ).InnerText;
string length = deviceNode.Sele ctSingleNode (
"Connection/ConfigCard/Length").InnerT ext;

Console.WriteLi ne ( "type = {0}, name = {1}, length = {2}",
type, name, length );
}
}
}

All you need to add is some error checking for if nodes don't exist, and
exception handling for catching problems if data is corrupted.
Beware the hard coded string for the xml file... All I did was cut and paste
your xml into "XmlFile1.x ml".

HTH.

Dan.

Nov 16 '05 #4

In the example I'm using it is done using XPath references... The functions
SelectNodes and SelectSingleNod e take in an XPath string.

2 more things to add on.

exception handling for catching problems if data is corrupted
--> Why do i need to catch problems if data is corrupted? Any examples?
Coz
i will be writing the script in xml manually, and process it in C#.
around all this you need to place "try {} catch {} finally" statements to
catch errors that may occur.
www.c-sharpcorner.com/ExceptionHandling.asp

Beware the hard coded string for the xml file
--> I don't get your meaning here. Hard coded string ???


I was simply refering the line
: myDoc.Load ( @"XmlFile1.x ml" );
make sure the filename is correct for what you need.

Let me know if you need more help.

Thanks.

Dan.
Nov 16 '05 #5
Oh i see...

Thanks Dan Bass. It really helped me a lot. Now i am on the right track :)
Cheers.

"Dan Bass" wrote:

In the example I'm using it is done using XPath references... The functions
SelectNodes and SelectSingleNod e take in an XPath string.

2 more things to add on.

exception handling for catching problems if data is corrupted
--> Why do i need to catch problems if data is corrupted? Any examples?
Coz
i will be writing the script in xml manually, and process it in C#.


around all this you need to place "try {} catch {} finally" statements to
catch errors that may occur.
www.c-sharpcorner.com/ExceptionHandling.asp

Beware the hard coded string for the xml file
--> I don't get your meaning here. Hard coded string ???


I was simply refering the line
: myDoc.Load ( @"XmlFile1.x ml" );
make sure the filename is correct for what you need.

Let me know if you need more help.

Thanks.

Dan.

Nov 16 '05 #6

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

Similar topics

1
6817
by: bdinmstig | last post by:
I refined my attempt a little further, and the following code does seem to work, however it has 2 major problems: 1. Very limited support for XPath features Basic paths are supported for elements, attributes, ".", and "..", plus also the "" predicate format is supported - however, only one predicate per path step is supported, and expr must be a relative path. 2. Poor performance
0
3482
by: Michael Fork | last post by:
Note: I pasted the code the attachments as plain text after the message (I wasn't able to post it with an attachment...) Attached are the XSL and XML files that I am having problems with. I am trying to extract the stock information after having downloaded the HTML and converted to XML (well-formed HTML) using XSL and XPATH and am unable. I am basing what I have done so far off of...
13
2502
by: tfsquare | last post by:
All, I am new to XSLT and having some problems understanding the syntax of XPath which selects nodes in the XML document. Consider this bit of XML, which contains three outer XML elements. <FOO>foo.top.level</FOO> <BOO><FOO>foo.second.level</FOO></BOO> <CHOO><BOO><FOO>foo.third.level</FOO></BOO></CHOO>
4
6078
by: Vitali Gontsharuk | last post by:
Hallo! When using the XPATH document() function to load a new XML document, we are coming across problems, because XALAN seems to have problems with absolute paths. XALAN always assumes that the path is relative to the current directory. So if we e.g. are in "c:\xslt_scripts" and are trying to load an XML file from "c:\xml_files\test.xml" it ist trying to open a file with the following absolute path:...
1
1828
by: helpful sql | last post by:
Hi all, Following is a part of an Xml document I am having problems with. I have a XmlNode variable in my C# application that referes to the mytable node of the following Xml. Now I need to get all children of mytable node from the ns0 namespace(myfield1 and myfield2 in this case) using the XmlNode object. I need a help with Xpath query to achieve this. Do you think the following statement would work?...
2
5608
by: Locusta | last post by:
Hello, I would like to use XPATH in a C program to retrieve values from XML documents. Did anyone tried this and can give me some advice? Cheers, Locusta
14
1997
by: Mat| | last post by:
Hello :-) I am learning XPath, and I am trying to get child nodes of a node whose names do *not* match a given string, e.g : <dummy> <example> <title>Example 1</title> <body>this is an example</body>
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
8850
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8523
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,...
0
7355
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
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
4334
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1975
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
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.