Is there an XmlEncode / XmlDecode for .NET?

2019-02-21 11:40发布

Are there methods for encoding and decoding XML in .NET? I can't seem to find them and am wondering why they aren't there and what to use instead?

I need to encode an XML document and pass it through to a string parameter on a web service. It then needs to be decoded at the other end.

4条回答
We Are One
2楼-- · 2019-02-21 11:49

Actually with the nice objects in System.Xml.Linq you need not worry.

What I mean is you will not get a runtime exception if you run this code.

var element = new XElement("Name", "<Node />");

The value of the element will be a text node with &lt;Node /&gt;.

查看更多
疯言疯语
3楼-- · 2019-02-21 11:55

If you are referring to encoding/decoding of XML names, there is XmlConvert.EncodeName and DecodeName.

Or are you talking about specifying the encoding/decoding of the whole XML document using XmlDeclaration or XDeclaration? (I thought this took care of encoding for us)

查看更多
贼婆χ
4楼-- · 2019-02-21 11:56

If you're passing XML as a string parameter (very bad web service design, BTW), then you don't have to do anything. It's up to the web service to do any encoding that may be necessary. Just use XDocument.ToString() or whatever and pass the result to the web service.

查看更多
Evening l夕情丶
5楼-- · 2019-02-21 12:03

It's not true!

Var element As XElement = <Name><%= GetValue() %></Name>

Private Function GetValue() As String
  Return "Value with < and > as well as a " & Chr(0) & " (Nul)"
End Function

does work with lesser and greater than signs but not with special chars like NUL or other low ASCII characters (it does not crash at the time adding the string but when calling ToString() or writing it somewhere).

If readability is not that important, use this method:

Public Function ToXmlString(ByVal aString As String) As String
    If (aString Is Nothing) Then Return ""
    Dim myResult As New StringBuilder(aString.Length + 10)
    For Each myChar As Char In aString
        If ("abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ.:,;!?-_$£{}()[]+*/\0123456789".IndexOf(myChar) > -1) Then
            myResult.Append(myChar)
        Else
            Select Case myChar
                Case "&"c
                    myResult.Append("&amp;")
                Case """"c
                    myResult.Append("&quot;")
                Case "<"c
                    myResult.Append("&lt;")
                Case ">"c
                    myResult.Append("&gt;")
                Case Else
                    myResult.Append("&#")
                    myResult.Append(AscW(myChar))
                    myResult.Append(";"c)
            End Select
        End If
    Next
    Return myResult.ToString()
End Function

to escape the values before you assign them.

If readability is important, implement all constants from http://de.selfhtml.org/html/referenz/zeichen.htm.

查看更多
登录 后发表回答