Storing Equal Signs (=) in XML Documents
I'm facing a problem that Google couldn't solve yet!
I'm trying to store URLs in an XML file. Problem is that these URLs contain Equal Signs (=) in them. And that generates an error.
Here is my code: (**token is a variable that contains the URL)
Dim child As String = vbCrLf & "<Link URL='" & token & "'></Link>"
Dim fragment As XmlDocumentFragment = doc.CreateDocumentFragment
fragment.InnerXml = child
The error message: (Error line and position are meaningless here)
'=' is an unexpected token. The expected token is ';'. Line 2, position 133.
I've replaced all '&' symbols with '&' i开发者_Python百科n case they were the ones causing the error, but no luck so far.
You should never use string manipulation to create XML. If you use the XML APIs of .NET, they will take care of all the special characters for you. Try:
XmlElement linkElement = doc.CreateElement("Link");
XmlAttribute urlAttribute = doc.CreateAttribute("URL");
urlAttribute.Value = token;
linkElement.SetAttributeNode(urlAttribute);
fragment.AppendChild(linkElement);
You should not replace &
with &
, you should replace them with &
.
Or better yet, create a node in your fragment and add an attribute to it. That way the object will encode the data correctly for you.
Dim fragment As XmlDocumentFragment = doc.CreateDocumentFragment()
Dim node As XmlElement = doc.CreateElement("Link")
Dim attr as XmlAttribute = doc.CreateAttribute("URL")
attr.Value = token
node.Attributes.Append(attr)
fragment.AppendNode(node)
Try adding this line below the first line:
-- insert this line; should make the "=" sign safe for XML...
token = System.Web.HttpUtility.UrlEncode(token)
Dim child As String = vbCrLf & "<Link URL='" & token & "'></Link>"
Dim fragment As XmlDocumentFragment = doc.CreateDocumentFragment
fragment.InnerXml = child
精彩评论