簡體   English   中英

如何在XSLT中合並兩個XML文件並使用C#中的已編譯轉換生成一個HTML輸出?

[英]How to merge two XML files in XSLT and produce one HTML output using compiled transform in c#?

我有兩個看起來像的XML文件:

...........
XML File 1:
...........
<Result>
  <Id>111</Id> 
  <Title>Result 111 title</Title>
  <Description>Result 111 Description</Description>
</Result>

...........
XML File 2:
...........

<Result>
  <Id>222</Id> 
  <Title>Result 222 title</Title>
  <Description>Result 222 Description</Description>
</Result>

我有XSLT產生這樣的設計:

|ID |
|Title :| |Result 111 Title|
|Description:| |Result 111 Description|     

我想要的是我也想從第二個XML文件中添加元素值,因此設計將如下所示:

|ID |
|Title :| |Result 111 Title|
|Description:| |Result 111 Description|

|ID |
|Title :| |Result 222 Title|
|Description:| |Result 222 Description|    

該設計將在C#的運行時中生成。 到目前為止,我已經將一種XML應用於One XSLT。 但這是不同的。 我怎樣才能做到這一點。 請使用“ ||” 成為“”標簽的設計。 任何幫助真的很感激。 謝謝..! :)

像這樣的東西(受此答案啟發):

var xslt = new XslCompiledTransform();
xslt.Load("merge.xslt", new XsltSettings{EnableDocumentFunction = true}, null );

var xmlr = XmlReader.Create("first.xml");
var xmlw = XmlWriter.Create("result.html");
var xslargs = new XsltArgumentList();
xslargs.AddParam("fileName", "", "second.xml");
xslt.Transform(xmlr, xslargs , xmlw);, xmlw);

和xslt:

  <xsl:output method="html" indent="yes"/>

  <xsl:param name="fileName" select="'somefile'" />
  <xsl:param name="updates" select="document($fileName)" />

  <xsl:variable name="updateItems" select="$updates/*" />

  <xsl:template match="@* | node()">
        <xsl:copy>
            <xsl:apply-templates select="@* | node()"/>
        </xsl:copy>
    </xsl:template>

  <xsl:template match="/">
    <merge>
    <xsl:copy>
      <xsl:apply-templates select="*" />
      <xsl:apply-templates select="$updateItems" />
    </xsl:copy>
    </merge>
  </xsl:template>

再次考慮,可以更輕松地實現此目的,您可以在其中添加要合並的任意數量的文件。

var xslt = new XslCompiledTransform();
xslt.Load("merge.xslt", new XsltSettings{EnableDocumentFunction = true}, null );

using (var xmlr = XmlReader.Create(
    new StringReader(@"<files><file>first.xml</file><file>second.xml</file></files>")))
{
    using (var xmlw = XmlWriter.Create("result.html"))
    { 
        xslt.Transform(xmlr, null , xmlw);
    }
}

Xslt

<xsl:template match="/">
    <html>
      <body>
        <xsl:for-each select="/files/file">
          <xsl:apply-templates select="document(.)/*" />
        </xsl:for-each>
      </body>
    </html>
  </xsl:template>

參考文獻:
加載
轉變

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM