I am having some difficulty with an xPath expression.
Context: I am using an XML document to store queries / stored procedure names in an ASP application. I use a utility function to load the xmldocument (if it isn't previously loaded) and I am attempting to select the node set from the document that matches an Id element. Here is my Xml document:
<Queries>
<Id>USER001
<Sql>spUsers_GetUserByUserName</Sql>
</Id >
<Id <USER002
<Sql>spUsers_GetUserByEmail</Sql>
</Queries>
Here is the code (I am using VB.NET)
Module Utility
private sqlXml as xmldocument
'....other stuff.....
Public Function GetSql(queryId as string) as string
dim qry as string
dim node as XmlNode
if开发者_StackOverflow中文版 sqlXml is nothing then
sqlXml = new xmldocument
sqlXml.Load (..path)
end if
qry = "//Id['" & queryId & "']" 'xPath to select the Id node = to paramter passed
node = sqlxml.SelectSingleNode(qry) 'set node <Id><Sql></Sql></Id>
return node.SelectSingleNode("//Sql").InnerText 'Return the Sql element value from the Id
End Function
The Problem:
the node variable only returns the first element. I have verified the that the qry
string that is used to SelectSingleNode
IS the correct Id value (i.e. USER002) - however the node is getting loaded with the USER001 element. It is obviously the xPath expression that is messed up. What do I need to tweak on the xPath expression so that I can return the correct <Id>
element and corresponding child <Sql>
element.
Any help would be appreciated.
Google XML COOKTOP and install it. It's a great little freeware app for trying out XPATH and XSLT expressions on XML data files and seeing the results.
It looks like you're trying to to construct an expression like //Id['USER002']
. That will select all the E elements for which the effective boolean value of 'USER002' is true - which is all of them. It's not clear what you intended because your XML sample is a mess, but it should be something like //Id[@id='USER002']
Also, you really shouldn't be constructing XPath expressions by string concatenation. It leaves you prone to injection attacks and to accidental misfunctioning when someone supplies a string containing quotes. It's also inefficient. Construct a string containing a variable reference $param, and set the parameter from the API. (Don't know how to do that in VB, I'm afraid).
精彩评论