Reputation: 153
I'm running this query and getting below mentioned error. Can anyone help?
Column name 'Middle Name' contains an invalid XML identifier as required by FOR XML; ' '(0x0020) is the first character at fault.
SELECT
Username as [LastName],
'' AS [Middle Name],
'' AS Birthdate,
'' AS [SSN],
0 AS [Wage Amount]
FROM
Employee
FOR XML PATH
Upvotes: 8
Views: 16967
Reputation: 536
For the simplest case, Smith's solution works all right. Since I have constraint to keep the chars, such as space, @, ', /, etc, on my XML, finally I solved this by encoding the identifier using Base64. (Just be careful the length of the name can not depass 128 bit) Then outside where the XML would be read as input data, another small code will translate Base64 easily to original string.
CREATE FUNCTION [dbo].[ufn_string_To_BASE64]
(
@inputString VARCHAR(MAX)
)
RETURNS VARCHAR(MAX)
AS
BEGIN
RETURN (
SELECT
CAST(N'' AS XML).value(
'xs:base64Binary(xs:hexBinary(sql:column("bin")))'
, 'VARCHAR(MAX)'
) Base64Encoding
FROM (
SELECT CAST(@inputString AS VARBINARY(MAX)) AS bin
) AS bin_sql_server_temp
)
END
GO
It's important to take VARCHAR
, taht will bring us shorter Base64 code.
You could add char(10)
, char(13)
in the identifier as well.
Dynamic SQL could be help to build a temporaire table to stock intermediate data.
In my case, C# decodes the Base64 to string
if (value.StartsWith("_"))
{
var base64Encoded = value.Substring(1).Replace('_','=');
try
{
var data = System.Convert.FromBase64String(base64Encoded);
value = Encoding.GetEncoding(1252).GetString(data);
}
catch (Exception e)
{
log.LogInformation(e.Message);
}
}
Be care of:
_
and remove them in c#.=
is not accepted in XML identifier. That should be replace by something else like _
.In real that would be more complexe than what's talking here.
Upvotes: 0
Reputation: 452988
You can't have spaces in XML element or attribute names. Use
SELECT Username AS [LastName],
'' AS [MiddleName],
'' AS Birthdate,
'' AS [SSN],
0 AS [WageAmount]
FROM Employee
FOR XML PATH
Upvotes: 17