我正在尝试创建xml文件:
DECLARE @XML as XML = ( Select
ProductID as "@Item",
Store as "@Store",
Price as "@Price",
Stock as "@Stock"
From ItemsDB
FOR XML PATH ('product'), ROOT ('products')
);
DECLARE @xmlChar AS VARCHAR(max) = CAST(@xml AS VARCHAR(max))
SET @xmlChar = REPLACE(REPLACE(@xmlChar, '>', '^>'), '<', '^<')
DECLARE @command VARCHAR(8000) = 'powershell -Command "Set-Content-Encoding UTF8 D:\XML\test.xml \"' + @xmlChar + '\""'
EXEC xp_cmdshell @command
}
但xml文件丢失了所有双引号,结果如下:
<products>
<product Item=100798 Store=121 Price=118.56 Stock=0.0000/>
<product Item=101628 Store=401 Price=593.14 Stock=0.0000/>
</products>
在哪里可以这样获得xml:
<products>
<product Item="100798" Store="121" Price="118.56" Stock="0.0000"/>
<product Item="101628" Store="401" Price="593.14" Stock="0.0000"/>
</products>
最佳答案
我用我的一些数据尝试了您的代码...这是返回的“命令”:
powershell -Command "Set-Content-Encoding UTF8 D:\XML\test.xml \"^<products^>^<product Item="84519" Store="xyz"/^>^<product Item="260" Store="abc"/^>^</products^>\""
<
,但不能转义>
这在我的系统中有效:
DECLARE @XML as XML =
( Select 'TestItem' as "@Item"
,'TestStore' as "@Store"
FOR XML PATH ('product'), ROOT ('products')
);
DECLARE @xmlChar AS VARCHAR(max) = CAST(@xml AS VARCHAR(max));
SET @xmlChar = REPLACE(REPLACE(@xmlChar, '<', '`<'),' ','` ');
DECLARE @command VARCHAR(8000) =
'powershell -Command Set-Content -Encoding UTF8 -path F:\Daten\testXY.xml -value "' + REPLACE(@xmlChar,'"','`''') + '"';
EXEC xp_cmdshell @command;
结果
<products><product Item='TestItem' Store='TestStore'/></products>
我没有找到用双引号编写相同内容的方法,但这通常是不重要的。 XML可以同时处理两者。如果使用应用程序(这里是Visual Studio,Win10 / Edge和Chrome)打开此文件,则会看到此信息:
每个应用程序都将其接受为有效的XML,不仅会按“原样”显示内容,还会进行某种解释。这应该证明它可行...
关于xml - XML通过保存到文件中丢失双引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35292680/