xpath string genration for attribute contaning an apostrophe.
-
4. srpna 2012 19:19
Hello,
Feel like I should apologize as similar questions have been asked but I cannot seem to get the idea to work for my applicaiton.
I am working in vb.net 2008
I have an xml file that is storing informastion in attributes. I unfortunately cannot change the structure of the xml file.
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <TeamNames> <Team AlternateTeamName="Alabama St." StandardizedTeamName="Alabama State"/> <Team AlternateTeamName="Alaska - Anchorage" StandardizedTeamName="Alaska-Anchorage"/> <Team AlternateTeamName="St. Joseph's" StandardizedTeamName="Saint Joseph's"/>
...
</TeamNames>
In my code I need to find teams with a given AlternateTeamName
I am trying to use the following but it is not selecting through the apostrophe correctly.
Dim xpath As String = "//Team[@AlternateTeamName=""" + sIndex + """]" Return GetNCAAName(xmlDoc.DocumentElement.SelectNodes(xpath), 0, sIndexThe xmlDocumentElement is not selecting any apostrophe containing teams.
What syntax do I want for my xpath string?
Also am I correct that in no way will I be able to have an ampersand bare in the xml file? The current xml file DOES escape the amersands with & in the team names, but the apostrophe's are plaintext.
Thanks in advance for the help.
Všechny reakce
-
5. srpna 2012 10:41
As long as you know the attribute value contains only single quotes but no double quotes you can nicely solve that by constructing the XPath string as follows:
Dim doc As New XmlDocument() doc.Load("../../XMLFile1.xml") Dim name As String = "St. Joseph's" Dim path As String = String.Format("//Team[@AlternateTeamName = ""{0}""]", name) Console.WriteLine(doc.SelectSingleNode(path).OuterXml)With XPath 1.0 (which Microsoft supports) the real problem is constructing XPath string literals which contain both single quotes and double quotes.
You should also note that since 2007 there is XPath 2.0 and XQuery 1.0 where there are better escape mechanisms, Microsoft does not have support for those versions in the .NET framework but there are third party solutions like Saxon 9, AltovaXML, XmlPrime.
And with VB 2008 respectively .NET 3.5 or later, if you want to stick with the Microsoft .NET framework class libraries, you can use LINQ to XML instead of XPath e.g.
Dim doc As XDocument = XDocument.Load("../../XMLFile1.xml") Dim name As String = "St. Joseph's" Console.WriteLine(doc...<Team>.FirstOrDefault(Function(t) t.@AlternateTeamName = name))
MVP Data Platform Development My blog
- Navržen jako odpověď Martin Honnen 5. srpna 2012 18:09