getting strongly typed results from an XPath query?

Hi;

Is there an easy way, when I am iterating through the nodes returned
from an XPath query, to get typed results. I need to know if it's a
DateTime, decimal, or string. This is more than just what node it is
because an XPath can be the result of a count or other operation where
the resulting type has nothing to do with any node type.

I optionally have a schema - but not always.

??? - thanks - dave


david@at-at-at@windward.dot.dot.net
Windward Reports -- http://www.WindwardReports.com
me -- http://dave.thielen.com

Cubicle Wars - http://www.windwardreports.com/film.htm
0
thielen (152)
11/12/2009 6:22:17 PM
dotnet.xml 7266 articles. 0 followers. Follow

5 Replies
1852 Views

Similar Articles

[PageSpeed] 34

Hello Dave,

We can call XPathNavigator.Evaluate method to evaluate a XPathExpression, 
and returns the typed result. The following example evaluates an 
XPathExpression and returns a Double using the Current node of the 
XPathNodeIterator as the context node,

----------------------------------------------------------------------------
------------------------
XPathDocument document = new XPathDocument("books.xml");
XPathNavigator navigator = document.CreateNavigator();

XPathNodeIterator nodes = navigator.Select("//book");
XPathExpression query = nodes.Current.Compile("sum(descendant::price)");

Double total = (double)navigator.Evaluate(query, nodes);
Console.WriteLine("Total price for all books: {0}", total.ToString());
----------------------------------------------------------------------------
-------------------------


Best regards,
Ji Zhou
Microsoft Online Community Support

0
colbertz (6)
11/13/2009 10:12:58 AM
David Thielen wrote:

> Is there an easy way, when I am iterating through the nodes returned
> from an XPath query, to get typed results. I need to know if it's a
> DateTime, decimal, or string. This is more than just what node it is
> because an XPath can be the result of a count or other operation where
> the resulting type has nothing to do with any node type.

XPath 1.0 only knows the types number (which is a double), string, 
boolean, node-set. So I am not sure why you expect a DateTime or decimal 
from an XPath expression, unless you use a third party XPath 2.0 
implementation where that is possible.

Also if you are "iterating through nodes" then it can't be a count or 
other expression not returning a node-set.

Generally, with Microsoft's XPath 1.0 implementation, XPathNavigator, if 
you use the Evaluate method
http://msdn.microsoft.com/en-us/library/system.xml.xpath.xpathnavigator.evaluate.aspx
you get a .NET object returned, the mapping of XPath types to .NET types 
is as follows:
   "The result of the expression (Boolean, number, string, or node set). 
This maps to Boolean, Double, String, or XPathNodeIterator objects 
respectively."

If you have an XPathNodeIterator and iterate over it then you are 
dealing with an XPathNavigator for the current item and XPathNavigator 
has properties 
(http://msdn.microsoft.com/en-us/library/system.xml.xpath.xpathnavigator_properties.aspx)
TypedValue and ValueType and additionally properties like ValueAsDateTime.


-- 

	Martin Honnen --- MVP XML
	http://msmvps.com/blogs/martin_honnen/
0
mahotrash (1777)
11/13/2009 11:11:53 AM
On Fri, 13 Nov 2009 12:11:53 +0100, Martin Honnen <mahotrash@yahoo.de>
wrote:

>David Thielen wrote:
>
>> Is there an easy way, when I am iterating through the nodes returned
>> from an XPath query, to get typed results. I need to know if it's a
>> DateTime, decimal, or string. This is more than just what node it is
>> because an XPath can be the result of a count or other operation where
>> the resulting type has nothing to do with any node type.
>
>XPath 1.0 only knows the types number (which is a double), string, 
>boolean, node-set. So I am not sure why you expect a DateTime or decimal 
>from an XPath expression, unless you use a third party XPath 2.0 
>implementation where that is possible.
>
>Also if you are "iterating through nodes" then it can't be a count or 
>other expression not returning a node-set.
>
>Generally, with Microsoft's XPath 1.0 implementation, XPathNavigator, if 
>you use the Evaluate method
>http://msdn.microsoft.com/en-us/library/system.xml.xpath.xpathnavigator.evaluate.aspx
>you get a .NET object returned, the mapping of XPath types to .NET types 
>is as follows:
>   "The result of the expression (Boolean, number, string, or node set). 
>This maps to Boolean, Double, String, or XPathNodeIterator objects 
>respectively."
>
>If you have an XPathNodeIterator and iterate over it then you are 
>dealing with an XPathNavigator for the current item and XPathNavigator 
>has properties 
>(http://msdn.microsoft.com/en-us/library/system.xml.xpath.xpathnavigator_properties.aspx)
>TypedValue and ValueType and additionally properties like ValueAsDateTime.

Please correct me if I'm worng - this means for a DateTime I will get
a string and need to know the format it is in.

Also, how does it know a result is a number if a node value is
<node>123.45</node> when the next one could be <node>dave</node>?

thanks - dave

david@at-at-at@windward.dot.dot.net
Windward Reports -- http://www.WindwardReports.com
me -- http://dave.thielen.com

Cubicle Wars - http://www.windwardreports.com/film.htm
0
thielen (152)
11/13/2009 6:38:16 PM
David Thielen wrote:

>> If you have an XPathNodeIterator and iterate over it then you are 
>> dealing with an XPathNavigator for the current item and XPathNavigator 
>> has properties 
>> (http://msdn.microsoft.com/en-us/library/system.xml.xpath.xpathnavigator_properties.aspx)
>> TypedValue and ValueType and additionally properties like ValueAsDateTime.
> 
> Please correct me if I'm worng - this means for a DateTime I will get
> a string and need to know the format it is in.

Has the XML document you are querying been validated successfully? Is 
the element type xsd:dateTime?

> Also, how does it know a result is a number if a node value is
> <node>123.45</node> when the next one could be <node>dave</node>?

If there is no schema respectively if the XML document has not been 
validated then the no type information is available. You can then try 
one of the ValueAsSomeType methods to check whether the untyped string 
in the element can be converted to the type, they will throw an 
exception if conversion is not possible.

If the XML has been validated then you can't have two elements of the 
same name (e.g. 'node') with different types in the same context.

-- 

	Martin Honnen --- MVP XML
	http://msmvps.com/blogs/martin_honnen/
0
mahotrash (1777)
11/13/2009 6:51:34 PM
On Fri, 13 Nov 2009 19:51:34 +0100, Martin Honnen <mahotrash@yahoo.de>
wrote:

>David Thielen wrote:
>
>>> If you have an XPathNodeIterator and iterate over it then you are 
>>> dealing with an XPathNavigator for the current item and XPathNavigator 
>>> has properties 
>>> (http://msdn.microsoft.com/en-us/library/system.xml.xpath.xpathnavigator_properties.aspx)
>>> TypedValue and ValueType and additionally properties like ValueAsDateTime.
>> 
>> Please correct me if I'm worng - this means for a DateTime I will get
>> a string and need to know the format it is in.
>
>Has the XML document you are querying been validated successfully? Is 
>the element type xsd:dateTime?

Generally we have to handle XML with no schema. So we'll have to do
the tryAs.

thanks - dave

david@at-at-at@windward.dot.dot.net
Windward Reports -- http://www.WindwardReports.com
me -- http://dave.thielen.com

Cubicle Wars - http://www.windwardreports.com/film.htm
0
thielen (152)
11/16/2009 5:59:46 PM
Reply:

Similar Artilces:

Get a FREE Valuable gift just for reading this!
I'm Just Like YOU!! Always looking for great opportunities, We'll I've found one that works! It seemed too good to be true, but I gave it a try, and Now It is Working for me!! I'm no marketing guru, But this is really simple, check it out, you even get a FREE gift just for visiting. http://www.profitdealings.com/dollarempire ...

Query record in SQL
I have a form that uses a query to produce a combo box as a list for the user to choose a PartNumber-Suffix combination (the query includes the fields PartNumber and Suffix from the PartSuffixTbl and using Expr1 joins them with a dash between them). The user is to enter a Line number in an unbound text box. Then the button I created uses SQL to save the line number to the PartSuffixTbl if the PartNumber and Suffix match that selected in the combo box. My problem is that the only line number that gets updated is the first record on my PartSuffixTbl. no matter what is selected in the c...

I am typing in WHITE.. with Double spacing.. how do i reset plz ?
...

'Operation must use an updateable query'
I have an issue with a query that I cannot figure out the answer to. I keep getting the error 'Operation must use an updateable query'. The query I am running is: UPDATE DGBTestVariations SET DGBTestVariations.JURISDICTION = IIF(DGBTestVariations.JURISDICTION = "NoMoneyMuni", (SELECT DGBJurisdictionCOO.JurisCodes FROM DGBJurisdictionCOO WHERE DGBJurisdictionCOO.ID=3), IIF(DGBTestVariations.JURISDICTION = "Municipalities", (SELECT DGBJurisdictionCOO.JurisCodes FROM DGBJurisdictionCOO WHERE DGBJuri...

corrupted memo field in multi-table query
I have a multi-table query in Access 2003. Several of the tables have memo fields. When I run the query, the memo fields are displayed as Asian characters or a symbol of a square. There is one expression that concatenates first and last name and a parameter on another field. It is only the memo fields that display these characters. I tried compacting and repairing the database, but that did not help. Text fields with the same text as the memo fields display fine. I've tried creating a similar query as a test but I don't see this error. What might have corrupted this query...

Basic Query
Hypothetical scenario:- I have a 5 column 2000 row spreadsheet and wish to manualy eliminate some entries because they are superfluous or duplicates. I create a new SS from just 2 columns to make it easier to work with.. I do my editing on the new SS. Can I now "apply" those changes to the original SS? Or am I breaking a basic rule and will now have "misaligned" records? I hope my query is clear in spite of my poor description. TIA Brian Tozer "KiwiBrian" <briantoz@ihug.co.nz> wrote in message news:cjuu5s$oh8$1@lust.ihug.co.nz... > Hypothetical sce...

Smartlist Search Query Doesn't Produce Data
Using the payroll history trx (PHT) option in smartlist, we attempt to search for transactions using the audit control code column name in the search definition. If we search on UPRCC00000001 thru 7, records are returned. If we set the filter to UPRCC00000999, no results are displayed. UPRCC0000099 has been verified as a valid control code in the system. I've found some KB articles that refer to other smartlist item searches not working, but non refernecing PHT and nothing about intermittant search problems. Any help is appreciated! ...

how do I make the cell expand to fit my text as I type?
I merged some cells across the width of a spreadsheet and i can't get the cell to increase it's height as more text is typed in wraps around. Only way I know, is to move your cursor to between the row number of therow you want to adjust and the next row. The cursor changes shape into an up/down arrow. Click and drag till you see all. Double clicking will also not work "pnwwoman" wrote: > I merged some cells across the width of a spreadsheet and i can't get the > cell to increase it's height as more text is typed in wraps around. If cells are merged. ...

xpath and use of //
has anyone seen a situation similar to the following ? <level1 > <level2 > <level3 anAttribute="value3" /> </level2> </level1> Dim filePath As String Dim node As XMLNode Dim xmlDoc As XMLDocument Dim xpath As String filePath = "c:\test\myXMLDoc.xml" xmldoc = New XMLDocument xmldoc.Load(filePath) xpath = "/level1/level2/level3" node = xmldoc.SelectSingleNode(xpath) 'no error , but node returns as Nothing xpath = "//level2/level3" node = xmldoc.SelectSingleNode(xpath) ' node returns as expected ...

Formula to obtain result from non exact sequence match
I know this has to be easier than I currently do it. I have seen examples similar using exact matches or dates but nothing using ranges. I can obtain the correct answer when my sales value is an exact match on the commission payment tier table but I have been unable to formulate this correctly for non exact matches. My v-lookup will round to the nearest commission after I have passed to the next level rather than the next higher increment. I have many different rates by products and states and need a consistent means to return the appropriate value based on the specific sales amo...

Filtering Query based on field values
Hi, I am having a hard time fool-proofing a form HOURS_ENTER. The form is used to register hours worked by temporary employees in a table called HOURS. First I select the employee through a combobox Select_Emp from the table EMPLOYEES and store the EMP_ID into a field in the table. As a visual check, I read the values for name, contract dates (BEGINDATE and ENDDATE, for which the latter can be open, read empty) and such from the table EMPLOYEES. Those values are, of course, not stored in HOURS, just the ID. Next I use a combobox Select_Week to select the week that they did their work in. For...

Query Question... 02-25-10
I have filenames listed in a DB with '.pdf', I would like to to run an update query to loose the '.pdf' since everything is scanned as a pdf. There are hundreds of entries. Can someone give me a hand with the script? Thanks David In an update query AFTER BACKING UP DATABASE use this -- Replace([YourField], ".pdf", "") -- Build a little, test a little. "116" wrote: > I have filenames listed in a DB with '.pdf', I would like to to run an update > query to loose the '.pdf' since everything is scann...

Different Receipts by either account type or payment type
There should be a way to have either a type of customer or payment type setup to have its own receipt types. We deal with wholesale, and retail customers and sometimes our customers don't want the drivers seeing the prices. And some customers want 80 col receipts, while others want 40. It doesn't pay to change the register, because the majority in numbers of our customers are retail. ---------------- This post is a suggestion for Microsoft, and Microsoft responds to the suggestions with the most votes. To vote for this suggestion, click the "I Agree" button in the ...

Getting 5.6.1 rejected by remote host errors when routing out via connector
Hi, We have an SMTP connector (using a Smarthost, not DNS) in our Exchange 2003 org that will route out mail that it does not find a recipient for for a certain domain in Recipient Policy. Let's call it: domain.com So if no one in our Active Directory has the email address someone@domain.com it will route that mail out via this connector directly to an Exim mail server that currently hosts the rest of the mailboxes (We are in a migration stage, getting the Exim users over to Exchange 2003). It is running Exim 4.43 (that's what it says when I telnet to it). Not all mail is getting t...

How to get xml data from AXWebbrowser control?
I am using the axwebbrowser control in VB.net to automate the navigation of a password protected website. After loading data and pressing the correct submit button I get to a page that has only XML data on it. How do I get this XML data out of the AXwebbrowser control so I and parse it using the xml tools? The strange part is when I create a string called xmltext = axwebbrowser1.document.body.outerhtml The xmltext has quite a bit of extra code in it and the xml tags are gone. Now this browser control displays the xml perfectly. but xmltext contains the following.... xmltext= "<bod...

Query on a subform
I have a form that displays an outing for members to sign up. There is a subform where I display the members of the organization (via a combo box), using a query to pull the current members. Now the users would like to only show members by program. So I was hoping to use the ProgramID field from the form to match against the ProgramID on the member records in the subform's query. Is this possible to talk back and forth from the form to the subform's query? How would I do this? Thanks Jeff You can reference the parent form's ProgramID control as a parameter in the ...

2010 Word beta file type problem
I've installed Office 2010 beta. Now word documents (.DOC) are not associated with Word. I attempted to re-associate them as is typical in Windows by choosing "open with" and then browsing to "winword.exe" in c:\program files(x86)\office14. But it will not accept winword.exe as a valid program! So, currently the only way I can get to use Word is to open Word 2010 and either do File>Open, or drag a DOC file into the header of Word. (if I try to drag a DOC file from Explorer onto the Word icon on the desktop, it won't accept it! What's go...

Excel programmimg? database query?
Hi there, I wonder if someone can help me out on this. I have one excel spreadsheet (1) in which I make some calculation (Cells G1:AH500) for some given starting values (A1:F500). In a adjacent spreadsheet (2) I make other types of calculations, into whic I plug initial values: these initial values are used to calculate cell E2:E200, which are used to calculate F2:F200 and so on, until we ge the results in I2:I200. Now, how can I tell excel to plug the values of A1:F1 in spreadshee (1) into spreadsheet (2), give me the output in the field AH1:(AH1)+100 of spreadsheet (1); then take the v...

how to I get 2010 beta OneNote to be active in 2010 beta outlook
I added OneNote Quick tab to Outlook, but it is not active. How do I make it active? "Quick Tab"? Can you clarify what you mean? What steps diod you take in Outlook (what version?) to get this to appear and what exactly doesn't work? =?Utf-8?B?U01H?= <SMG@discussions.microsoft.com> wrote in news:131F64B7-0948-4C1A-B684-0ADCD0BBB3A9@microsoft.com: > I added OneNote Quick tab to Outlook, but it is not active. How do I > make it active? > I am running the Office 2010 Professional Plus Beta. I said quick tab, after checking it is actually...

Async error
I'm not sure exactly when this has happened. When I 'Test Access' I get 503 errors. I restarted the Async service and noticed the below error in the event log. I noticed a similar issue at; http://groups.google.com/group/microsoft.public.crm/browse_thread/thread/48a444a5e2ce116b I did not import the organisation, nor update the async table manually. I ran the script on the database and it returned 31,874 records. Im not quite sure what that means though. Any help greatly appreciated. Event Type: Error Event Source: MSCRMAsyncService Event Category: None Event ID: ...

Combine Query
SQL 2008 I have a table with a XML field that stores an XML file. I have no problems grabbing data from this field using the query below. DECLARE @x xml; Set @x = (Select ReportFile FROM XMLREports where LedgerKey = @LedgerRef); BEGIN SELECT T5.c1.value('@ref[1]', 'varchar(max)') AS [RDI_name] , T5.c1.value('@transCode[1]', 'varchar(max)') AS [RDI_number], T5.c1.value('@returnCode[1]','varchar(max)') AS [RDI_sortCode], T5.c1.value('@returnDescription[1]', 'varchar(max)') AS [RDI_type], T5.c1.value('...

I'm getting the below error message
Account: 'pop.secureserver.net', Server: 'pop.secureserver.net', Protocol: POP3, Server Response: '-ERR authorization first', Port: 110, Secure(SSL): No, Server Error: 0x800CCC90, Error Number: 0x800CCC18 Any suggestions on how to fix? Go to Tools, Accounts, select that mail account, Properties, Servers. Make sure that "Log on using Secure Password Authentication" is not = enabled. =20 --=20 Gary VanderMolen, Microsoft MVP (Mail) http://mvp.support.microsoft.com/default.aspx/profile/vandermolen "ehale117" <ehale117@discussions...

Get Folder from Full File Path
What is the function to return a string containing just folder given a complete file path ? For example C:\Windows\abc.txt will return C:\Windows Here are some functions you may find useful (since you are using MFC): Tom // // Returns the file portion from a path // CString GetFileOnly(LPCTSTR Path) { // Strip off the path and return just the filename part CString temp = (LPCTSTR) Path; // Force CString to make a copy ::PathStripPath(temp.GetBuffer(0)); temp.ReleaseBuffer(-1); return temp; } // // Returns the folder portion from a path // CString GetFolderOnly(...

Attachments larger about 5M getting stripped
I am using Outlook 2003 on an XP Pro system. I am having difficulties receiving attachments larger than about 5M(my ISP allows up to 20M). When I watch the progress of an email downloading, it will show the size of the file it is attempting to download, but when the email has finished downloading, the attachment is gone. I have other users who have the same version of Outlook, using the same ISP, who don't have the same difficulty. I have "Download complete item including attachments" checked under Send and Receive settings, and there is not a size limit entered. what fir...

getting a compile error not sure why
I have written an event procedure for after the cost combo box is selected that if the value is NOT equal to 0 I do not want the field truckhours to be able to be input and if it is 0 they truck hours can be input. Private Sub cbocost_AfterUpdate() If (Me.cost) <> 0 Then Me.TruckHours1.Enabled = False Else Me.TruckHours1.Enabled = True End If End Sub not sure what I have wrong thanks, Barb It would help to know the exact error message you're getting. However, you imply that decision is based on what was selected in the combo box. In one place, the combo box is called cbocost,...