Xml/Xslt - how to read XML node that conatins @ nad single quotes in attribute
Asked By Sachin Mishra on 10-May-12 12:15 PM
I have an XML which contains @ and single quotes in attribute value and when I want to get the value of that node which contains the @ and single quotes I got an error “Invalid token” finally I tried to escape single quotes but I did not any value it showed me nothing in SelectSingleNode()
Here is the sample XML which contains @ and single quotes in title node and I want to get those nodes that has XPATH = Test[@ABC='4'],please suggest me the syntax to select that node.
<? xml version="1.0" ?>
<Book>
<Author>ABC</ Author >
<title val="Test[@ABC='4']">title1</title>
<title val="Test[@ABC='3']">title2</title>
</Book>
Vikram Singh Saini replied to Sachin Mishra on 12-May-12 01:21 PM
The problem you were facing was due to use of single quotes in XPathExpression. And that is why it was throwing error as Invalid key token. Try below working code as it is. This code reads the attribute values of elements successfully.
01.using System;
02.using System.Xml;
03.
04.namespace ReadXml
05.{
06. class Program
07. {
08. static void Main(string[] args)
09. {
10. XmlDocument egg = new XmlDocument();
11. egg.Load(@"Path to\test.xml");
12.
13. XmlNodeList eggElement = egg.SelectNodes("//Book/title");
14.
15. foreach (XmlElement element in eggElement)
16. {
17. string val = element.GetAttribute("val");
18. string xPathExpression = "//title[@val=" + EncodeXpathString(val) + "]";
19.
20. XmlElement eggItem = (XmlElement)egg.SelectSingleNode(xPathExpression);
21. Console.WriteLine("Found value of attribute val: "+eggItem.GetAttribute("val"));
22. Console.ReadLine();
23. }
24.
25. }
26.
27. // Function to handle single quotes that result in error as
28. // System.Xml.XPath.XPathException: '//title[@val='Test[@ABC='4']']' has an invalid token.
29. private static string EncodeXpathString(string args)
30. {
31. string result = "";
32. if (args.Contains("'"))
33. {
34. string[] inputStrings = args.Split('\'');
35. foreach (string input in inputStrings)
36. {
37. if (result != "")
38. result += ",\"'\",";
39. result += "\"" + input + "\"";
40. }
41. result = "concat(" + result + ")";
42. }
43. else
44. {
45. result = "'" + args + "'";
46. }
47. return result;
48. }
49. }
50.}
Let us know whether the solution helped you in achieving the objective.
LIJO PHILIP replied to Sachin Mishra on 18-May-12 12:33 AM
If you need read attribute node from xml you can use:
- http://msdn.microsoft.com/en-us/library/system.xml.linq.xdocument.aspx class - easy to use - it's Linq to XML
- http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.aspx class
- http://msdn.microsoft.com/en-us/library/system.xml.xmlreader.aspx class - "Represents a reader that provides fast, non-cached, forward-only access to XML data." (msdn)
LIJO PHILIP replied to Sachin Mishra on 18-May-12 12:39 AM
sorry for the above. links got messed up. try this
If you need read attribute node from xml you can use:
XDocument class - easy to use - it's Linq to XML
Link: http://msdn.microsoft.com/en-us/library/system.xml.linq.xdocument.aspx
XmlDocument class
Link: http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.aspx class
XmlReader class - "Represents a reader that provides fast, non-cached, forward-only access to XML data."
Link:http://msdn.microsoft.com/en-us/library/system.xml.xmlreader.aspx
(msdn)

escape xml with xpathnavigator.appendchild .NET Framework
I'm using an xpathnavigator in a windows form to append child with attributes. xnav.AppendChild("<item name = """" value = """ & client supplied value & When the client enters a value with illegal characters like "<", the naviagtor does not escape them. How do I escape the input in a Windows form? Rick Xml Discussions WriteStartElement (1) WriteEndElement (1) AppendChild (1) ClientSuppliedValue (1) XmlWriter (1) Xpathnavigator (1) Naviagtor (1 item") xml_writer.WriteAttributeString("name", "") xml_writer.WriteAttributeString("value", clientSuppliedValue) xml_writer.WriteEndElement() End Using - - Martin Honnen - -- MVP XML http: / / JavaScript.FAQTs.com / thanks again Martin Rick keywords: escape, xml, with, xpathnavigator.appendchild description: I'm using an xpathnavigator in a windows form to
Is there XmlDecode / XmlEncode? .NET Framework
I have a string containing XML embedded withing another XML document as an attribute value. This is what the string looks like: <message> quick brown message> quick brown fox< / message> How? (I don't think XmlConvert handles this.) regards, T Xml Discussions XPathDocument (1) Xml (1) Console (1) Main (1) What happens if you do this: XmlDocument doc = new XmlDocument LoadXml(myWholeDocument); / / Assuming <child attributeWithXML = "<message> quick brown fox<message / > " / > string embeddedXml = doc.DocumentElement["child"].Attributes["attributeWithXML"].Value; Console.WriteLine(embeddedXml); What prints out? - - John Saunders [MVP] Thanks John, The following indeed print <message> quick brown fox< / message> . But I know exactly where in the containing XML this string occurs. I am able to extract this without the expense of parsing. I am looking for a shortcut to unescape the embedded XML. But thanks the answer is obvious from here. [code] using System; using System Xml; class Starter { public static void Main(string[] args){ XmlDocument doc = new XmlDocument(); string xml = "<d
Attribute or Element? .NET Framework
Hi, I'm working with creating a XML Schema. I almost directly became uncertain wheter / when to use attributes and when to use elements. Which is best: this: . . . or this: . . . Are there any recommendations on when to use what? regards Carl Xml Discussions MobilePhone (1) HomePhone (1) WorkPhone (1) EC95376FCC3B (1) Attributes (1) Wheter (1) CDATA (1) Meta (1) There are lots of differing views on this subject. In general I, and many others, prefer attributes for properties that are "one offs" and meta data and elements when there could be exception to this is when the property can contain large amounts of text, then using attributes can be unwieldy especially as you cannot have the equivalent of a CDATA section with an attribute's value so need to escape some characters. It also helps for later retrieval and processing if you make things as name. In the case of something like phone numbers where you could choose to have attributes for homePhone, workPhone and mobilePhone for instance I would tend to go with: although many
XML DOM / ASP : escaping apostrophe in XPath expressions .NET Framework
Hello, I'm trying to find no success so far. (Most of them XSLT though, while I'm dealing with the XML DOM). Below is a sample script. I'm trying to write a function (Escape) that would return a string that can be safely placed in the XPath expression. I the way, I'd also like to extend the function to deal with quotes (") in attributes. . . I'd greatly appreciate your help! F. Dim XMLDoc1, Node1, a, XPath1 Set XMLDoc1 = Server Albert O'Hare""> Rupert O'Donnell< / item> < / doc> ") 'a = "Albert O'Hare" 'XPath1 = " / / item[@name = " & Escape(a) & "] / @id" a = "Rupert O'Donnell" XPath1 = " / / item[text() = " & Escape(a) & "] / @id" Response.Write "XPath: " & XPath1 & "<br / > " Set Node1 = XMLDoc1.SelectSingleNode(XPath1) If Not(Node1 Else Response.Write "No matching node" End If Set Node1 = Nothing Set XMLDoc1 = Nothing Function Escape(Text) Escape = "concat('" & Replace(Text, "'", ", '''', ") & "')" End Function %> Xml Discussions XPath (1) ReplaceApostrophe (1) SelectSingleNode (1) XMLDoc (1
cdata-section-elements .NET Framework
I am creating an xml document that I would like to have one element as a cdata section. I am applying a xsl to take out all empty attributes. When using the xsl, the cdata section never gets applied to the element onscreenItem. Any thoughts? XML class = "bold"> bold< / span> < / p> < / onscreenItem> XSL Transform"> instruction()"> Xsl Discussions OnscreenItem (1) Cristian (1 that cannot go inside a CDATA as CDATA represents text and not markup in an XML document. Best Regards, George - -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- George Cristian Bina - http: / / aboutxml.blogspot.com / http: / / www.oxygenxml.com also that CDATA is just a convenience to write some text without the need to escape special characters like < and &. Regards, George - -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- George Cristian Bina - http: / / aboutxml.blogspot.com / http: / / www had shown some while ago in a reply to an older post. - - Martin Honnen - -- MVP XML http: / / JavaScript.FAQTs.com / keywords: cdata-section-elements description: I am creating an xml document that I would like to have one element as a cdata section. I am applying a xsl to take out all empty attributes. When using
Serializing / Deserializing XML using System.Xml.Serialization .NET Framework
I am trying to create such class that could be serialized / deserialized to / from an XML. I have chosen to use System.Xml.Serialization.XmlSerializer serializer for that. There is a caveat though. I would like to have one of my class's members to be a string, which would contain an XML text. Here is what I mean. My XML file: I would like to be able to deserialize my RootElement and by refering to Child2 be able to access the XML string Here is what I have done so far: [Serializable] public class Child1 { private string m_szName = value; } } } [Serializable] public class Child2 { private string m_szXml; public Child1() { } [XmlAttribute("Name")] public String Xml { get { return m_szXml; } set { m_szXml = value; } } } [Serializable] public class RootElement { private Child1 m_oChild1; private Child2
XML parsing error: An invalid character was found in text content SQL Server
Hi, We have a simple web application, classic ASP (VBScript) based, which uses XML-explicit stored procedures for most of its data transfer functions. The application has been running do with the new server settings, but we don't know what. If I manually escape out the offending characters using, for example, viable solution of course. The error messge is: [Microsoft][ODBC SQL Server Driver][SQL Server]XML parsing error: An invalid character was found in text content. The problem is that, although AT SQL Server Programming Discussions SQL Server (1) CREATE PROCEDURE (1) Text (1) Database (1) Xml (1) Stored procedure (1) Escape (1) Session (1) Hi Andrew, I think you have 2 problems here: (1) Text encoding People sometimes have issues with extended-ASCII characters when they have encoded the XML text as ASCII but set the encoding to UTF-8 in the XML declaration (or vice-versa). ASCII and UTF-8 encoding are identical till you get to
Oct-12 07:37 PM I'm storing a table value in hidden field as xml(in code behind) and parsing that xml with java script. . I'm using "Server.HtmlEncode" to encode and "Encoder.htmlDecode" to decode be rendered in the browser. Hi, U may store the escaped text in the Textbox XML encoding is necessary if you have to save XML text in an XML document. If you don't escape special chars the XML to insert will become a part of the original XML DOM and not a value of a node. Escaping the XML means basically replacing 5
Why do you use XML? .NET Framework
Hello, everyone: I have a simple request to anyone interested. We at work are aware of the (so-called) importance of XML. We have laboriously attempted to find practical uses of XML. However, in our environment, working with XML seems like a complete waste of time. For instance, we pull data from a database to a database. Recently I attempted to pull a space separated value file into an XML format and used XSLT to convert it to a comma separated value file. Well, XSLT doesn't work naturally for anything but XML. It was a waste of time and it would have been easier to just send databases and nothing in-between, I am really starting to wonder if knowing anything about XML is really all that useful to my life right now. That is why I would like for everyone reading to tell me you opinions and practical experiences with XML. Do you use XML as regularly as hype seems to say you should? Do you
22 PM In a previous post I had a question on how to create an xml file. In the end I solved the problem by using response.write every single xml line. However, somebody mentioned that this is very inefficient and I should use xmlwriter . I only understood that the xmlwriter class directly converts your data from the dbase to an xml file but I need to add some extra lines that don't come from the What I basically want to achieve is to have an aspx page that outputs some xml code. See how I solved it below and if somebody could direct me in a SqlDataReader Dim Cmd As New SqlCommand(Sql, conn) conn.Open() objDR = Cmd.ExecuteReader() Response.Write("<?xml version = ""1.0"" encoding = ""utf-8""?> " & vbLf) Response.Write("<slideshow loop = ""true"" stream = ""true""> " & vbLf Close() Response.Write("< / slideshow> ") End Sub End Class is designed to efficiently create WELL-FORMED Xml and prevent mistakes, unlike "taking a chance" by using a different method. The class provides a fast, non-cached, forward-only means of generating streams or files containing XML data that conforms to the W3C Extensible Markup Language XML) 1.0 and the Namespaces in XML recommendations. If you follow the documentation, it is