xml - XML通过保存到文件中丢失双引号

标签 xml tsql powershell

我正在尝试创建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^>\""
  • 您正在使用错误的转义(powershell等待反引号)
  • 您必须转义<,但不能转义>
  • 我也必须逃脱空格
  • 您的powershell命令语法错误

  • 这在我的系统中有效:
    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)打开此文件,则会看到此信息:

    with Visual Studio

    With Win10/Edge

    or Chrome

    每个应用程序都将其接受为有效的XML,不仅会按“原样”显示内容,还会进行某种解释。这应该证明它可行...

    关于xml - XML通过保存到文件中丢失双引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35292680/

    相关文章:

    xml - XPath:默认为 'Node A' ,如果 'Node B' 不为空,则选择 'Node B'

    sql-server - 如何将参数传递给将执行存储过程的 SQL 作业

    sql - 在表中查找尾随空格

    powershell - 在PowerShell 5.0中打印本地组成员

    excel - 如何使用 PowerShell 将 VBA 代码添加到 Excel 工作表?

    .net - 如何列出解决方案中所有过时的包?

    java - 使用 AsyncTask 在主 Activity 的单独类中获取控件

    c# - 如何防止 XmlSerializer 转义 "nested XML"?

    xml - Hadoop Pig XPath返回空属性值

    sql - 在 SQL Server 上仅显示一个数据库