简体   繁体   中英

Swift string does not escape double quotes

Very strange issue, I feel like I'm missing something very simple but cannot figure it out. I'm trying to build an XML body like so:

let bodyString = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><UserNameLoginRequest xmlns=\"\(PSS_XML_DEFAULT_NAMESPACE)\" from=\"\(LoginManager.clientID)\"><UserName>\(username)</UserName><UserPassword>\(password)</UserPassword><ClientType>\(clientType)</ClientType></UserNameLoginRequest>"

But what comes out is this (URL and credentials redacted):

<?xml version=\"1.0\" encoding= \"UTF-8\"?><UserNameLoginRequest xmlns=\"http://example.com/\" from=\"myDeviceID\"><UserName>000</UserName><UserPassword>1234</UserPassword><ClientType>myClientType</ClientType></UserNameLoginRequest>

Note the backslashes. Obviously this isn't valid XML and doesn't work. So...what am I missing?

let username = "user"
let password = "pswd"
let clientType = 0
struct LoginManager {
    static let clientID = 100
}

let bodyString = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><UserNameLoginRequest xmlns=\"\\(PSS_XML_DEFAULT_NAMESPACE)\" from=\"\(LoginManager.clientID)\"><UserName>\(username)</UserName><UserPassword>\(password)</UserPassword><ClientType>\(clientType)</ClientType></UserNameLoginRequest>"
print(bodyString)

backslash MUST be escaped too!!!

<?xml version="1.0" encoding="UTF-8"?><UserNameLoginRequest xmlns="\(PSS_XML_DEFAULT_NAMESPACE)" from="100"><UserName>user</UserName><UserPassword>pswd</UserPassword><ClientType>0</ClientType></UserNameLoginRequest>

example

print("a\"\\b") //prints      a"\b

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM