从xml标签提取csv内容

时间:2019-05-10 09:16:19

标签: xslt xpath

我的源xml如下

<rest-adapter-response>
  <metadata>
    <status>success</status>
  </metadata>
  <status-line>
    <code>200</code>
    <reason>OK</reason>
  </status-line>
  <header-lines>
    <Cache-Control>private, max-age=0</Cache-Control>
    <Transfer-Encoding>chunked</Transfer-Encoding>
    <Content-Type>application/octet-stream</Content-Type>
    <Expires>Thu, 25 Apr 2019 08:51:55 GMT</Expires>
    <Last-Modified>Fri, 10 May 2019 08:51:55 GMT</Last-Modified>
    <Server>Microsoft-IIS/10.0</Server>
    <X-SharePointHealthScore>1</X-SharePointHealthScore>
    <X-SP-SERVERSTATE>ReadOnly=0</X-SP-SERVERSTATE>
    <DATASERVICEVERSION>3.0</DATASERVICEVERSION>
    <X-Download-Options>noopen</X-Download-Options>
    <Content-Disposition>attachment</Content-Disposition>
    <SPClientServiceRequestDuration>224</SPClientServiceRequestDuration>
    <X-AspNet-Version>4.0.30319</X-AspNet-Version>
    <SPRequestGuid>de31db9e-70cb-8000-7fba-6c3e85d9c810</SPRequestGuid>
    <request-id>de31db9e-70cb-8000-7fba-6c3e85d9c810</request-id>
    <MS-CV>ntsx3stwAIB/umw+hdnIEA.0</MS-CV>
    <Strict-Transport-Security>max-age=31536000</Strict-Transport-Security>
    <X-FRAME-OPTIONS>SAMEORIGIN</X-FRAME-OPTIONS>
    <X-Powered-By>ASP.NET</X-Powered-By>
    <MicrosoftSharePointTeamServices>16.0.0.8824</MicrosoftSharePointTeamServices>
    <X-Content-Type-Options>nosniff</X-Content-Type-Options>
    <X-MS-InvokeApp>1; RequireReadOnly</X-MS-InvokeApp>
    <P3P>CP="ALL IND DSP COR ADM CONo CUR CUSo IVAo IVDo PSA PSD TAI TELo OUR SAMo CNT COM INT NAV ONL PHY PRE PUR UNI"</P3P>
    <Date>Fri, 10 May 2019 08:51:55 GMT</Date>
  </header-lines>
  <message-body>
    <non-xml-data-response>COA,COA Acct Desc,Acct Prefix,Revaluation Acct,Mapping Changes - Additions( A )  Deletions ( D ) Changes ( C ),MJE,OIM Recon,Comments for difference:10000274,"Citibank, Operating, USD, 31165975",1000,10009999,A,,X,10000374,"Citibank, Clearing, USD, 31165975",1000,10009999,A,,X,10006604,"HSBC, Operating, SAR, SA0345000000003179660002",1000,10009999,A,,X,10006605,"Citibank, Operating, ZAR, 0202099009",1000,10009999,A,,X,123,,,456,,,,</non-xml-data-response>
  </message-body>
</rest-adapter-response>
XML上方的

是共享点Web服务的响应,该Web服务试图读取csv文件并给出了这样的响应。如您在上面的响应xml中看到的那样,csv数据确实出现了,但是在一个名为<message-body>的xmltag中,并且在每行格式之后也丢失了新行!

现在我需要重新创建csv !!。最糟糕的是,在我收到这种格式的工具中,我有能力编写xslt和xml!不能使用托管语言代码或库。 也只有xslt 1.0。

有这样的问题 question on creating csv from xml,但这与我的要求有些不同。我只是在学习xslt和xpath,在这方面有人可以帮助我吗?

以下是请求的输出: click here to view the csv format

1 个答案:

答案 0 :(得分:1)

如果人们假设标题行以冒号结尾,并且每个数据行中有7个值*,则可以使用以下样式表:

XSLT 1.0

public void ReceiveFromGattCharacteristic(string service, string characteristic, string descriptor = null)
    {
        DebugHelper.Message(Type.Method, "ReceiveFromGattCharacteristic");

        bleAdapter.DeviceConnected += async (s, e) =>
        {
            try
            {
                DebugHelper.Message(Type.Info, "bleAdapter.DeviceConected += async (s, e) ...");

                string[] deviceInfo = { e.Device.Name, e.Device.Id.ToString() };

                // Connect to service
                try
                {
                    DebugHelper.Message(Type.Info, "Connecting to service...");
                    _service = await e.Device.GetServiceAsync(Guid.Parse(service));
                    DebugHelper.Message(Type.Info, "OK");
                }

                catch (Exception)
                {
                    DebugHelper.Error(ErrorType.GATT, "Could not connect to service");
                }

                // Connect to characteristic
                try
                {
                    DebugHelper.Message(Type.Info, "Connecting to characteristic...");
                    _characteristic = await _service.GetCharacteristicAsync(Guid.Parse(characteristic));
                    DebugHelper.Message(Type.Info, "OK");
                }

                catch (Exception)
                {
                    DebugHelper.Error(ErrorType.GATT, "Could not connect to characteristic");
                }

                await ConfigureSpectrogram(UpdateFrequency.High, 0x1);

                try
                {
                    await _characteristic.StartUpdatesAsync();
                }

                catch
                {
                    DebugHelper.Error(ErrorType.GATT, "Error starting UpdatesAsync");
                }
                // ADDITION
                _characteristic.ValueUpdated += (o, args) =>
                {
                    var raw = args.Characteristic.Value;

                    Xamarin.Forms.Device.BeginInvokeOnMainThread(() =>
                    {
                        DataPageViewModel.Levels.Clear();

                        for (int i = Models.Spectrogram.FrequencyOffset; i < raw.Length; i++)
                        {
                            if (SettingsViewModel.IsViewRawData)
                            {
                                DataPageViewModel.Title = "Raw data";

                                DataPageViewModel
                                .Levels
                                .Add(
                                    new Models.Spectrogram(
                                        raw[i],
                                        1 + (i - Models.Spectrogram.FrequencyOffset))
                                        );
                            }

                            if (SettingsViewModel.IsViewProcessedData)
                            {
                                DataPageViewModel.Title = "Processed data";

                                DataPageViewModel
                                .Levels
                                .Add(
                                    new Models.Spectrogram(
                                        raw[i],
                                        1 + (i - Models.Spectrogram.FrequencyOffset),
                                        i));
                            }
                        }
                    });
                };
            }
            // END OF ADDITION

            catch (Exception)
            {
                DebugHelper.Error(ErrorType.GATT, "Error in ReceiveFromGattCharacteristic");
            }
        };
    }

应用于您的输入示例,结果将是:

结果

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" encoding="UTF-8"/>

<xsl:template match="/rest-adapter-response">
    <xsl:variable name="csv" select="message-body/non-xml-data-response" />
    <!-- header -->
    <xsl:value-of select="substring-before($csv, ':')" />
    <xsl:text>:&#10;</xsl:text> 
    <!-- data -->
    <xsl:call-template name="restore-csv">
        <xsl:with-param name="text" select="substring-after($csv, ':')"/>
    </xsl:call-template>
</xsl:template>

<xsl:template name="restore-csv">
    <xsl:param name="text"/>
    <xsl:param name="i" select="1"/>
    <xsl:choose>
        <xsl:when test="contains($text, ',')">
            <xsl:variable name="value">
                <xsl:choose>
                    <xsl:when test="starts-with($text, '&quot;')">
                        <xsl:text>"</xsl:text>
                        <xsl:value-of select="substring-before(substring-after($text, '&quot;'), '&quot;')"/>
                        <xsl:text>"</xsl:text>
                    </xsl:when>
                    <xsl:otherwise>
                        <xsl:value-of select="substring-before($text, ',')"/>
                    </xsl:otherwise>
                </xsl:choose>
            </xsl:variable> 
            <!-- output -->         
            <xsl:value-of select="$value"/>
            <xsl:choose>
                <xsl:when test="$i mod 7 = 0">
                    <xsl:text>&#10;</xsl:text>
                </xsl:when>
                <xsl:otherwise>
                    <xsl:text>,</xsl:text>
                </xsl:otherwise>
            </xsl:choose>
            <!-- recursive call -->
            <xsl:call-template name="restore-csv">
                <xsl:with-param name="text">
                    <xsl:choose>
                        <xsl:when test="starts-with($text, '&quot;')">
                            <xsl:value-of select="substring-after(substring-after($text, '&quot;'), '&quot;,')"/>
                        </xsl:when>
                        <xsl:otherwise>
                            <xsl:value-of select="substring-after($text, ',')"/>
                        </xsl:otherwise>
                    </xsl:choose>
                </xsl:with-param>
                <xsl:with-param name="i" select="$i + 1"/>
           </xsl:call-template>
        </xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="$text"/>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>

</xsl:stylesheet>

这可能需要更多的工作来处理带引号的值中可能的转义双引号。


-
(*)奇怪的是,标题行中有8个值,而数据行中只有7个值。