XML转义字符

时间:2010-11-11 17:46:41

标签: xml vb.net httpwebrequest

我正在尝试发送POST请求以将一些内容添加到API框中。规则是正文格式应为XML(值必须是XML转义),HTTP方法(发布),要求身份验证(是),请求内容(内容类型:“application / xml”

<entries?
  <entry tag="some_tag">
   <value>XML-escaped-entry belongs here</value>
  </entry>
  <entry tag="some_tag">
   <value>XML-escaped-entry belongs here</value>
....
...

 </entries>

我按如下方式发送请求,并收到400错误请求错误。当我输入一个值进入时它起作用。

 For i As Integer = 0 To searchItems.Count - (1000 - max)
                data = data + "<entries><entry><value>" & searchItems.Item(i) & "</value></entry></entries>" & vbNewLine
            Next
            If uri.Scheme = uri.UriSchemeHttps Then
                Dim request As HttpWebRequest = HttpWebRequest.Create(uri)
                request.Method = method__1
                request.ContentLength = data.Length
                request.ContentType = "application/xml"
                request.Credentials = New System.Net.NetworkCredential("xxx@xxx.com", "xxxxxx")
                Dim writer As New StreamWriter(request.GetRequestStream)
                writer.Write(data)
                writer.Close()
                Dim oResponse As HttpWebResponse = request.GetResponse()
                Dim reader As New StreamReader(oResponse.GetResponseStream())
                Dim tmp As String = reader.ReadToEnd()
                oResponse.Close()
            End If

其他规则:   - 最佳做法是逐步添加和删除条目列表中的更改,而不是每次需要更改时删除/重新创建整个列表。   - 新的条目放在队列的顶部以进行轮询,并以LIFO方式处理。

2 个答案:

答案 0 :(得分:5)

您需要在循环期间查找并编码特殊字符。有点像:

 For i As Integer = 0 To searchItems.Count - (1000 - max)
            data = data + "<entries><entry><value>" & encodeEntry(searchItems.Item(i)) & "</value></entry></entries>" & vbNewLine
 Next

 Private Function encodeEntry(ByVal entry As String) As String
     Dim returnValue As String = entry

     ' Replace the special characters
     returnValue = returnValue.Replace("&", "&amp;")
     returnValue = returnValue.Replace("""", "&quot;")
     returnValue = returnValue.Replace("'", "&apos;")
     returnValue = returnValue.Replace("<", "&lt;")
     returnValue = returnValue.Replace(">", "&gt;")

     ' return the escaped string
     return returnValue
 End Function

答案 1 :(得分:3)

  1. 请勿使用+运算符连接字符串,请使用StringBuilder
  2. 不要使用StringBuilder来构建XML,使用XmlWriter,它会解决您的编码问题。