【问题标题】:How can I add an XSL stylesheet inside an XML file with C#?如何使用 C# 在 XML 文件中添加 XSL 样式表?
【发布时间】:2016-02-19 11:09:27
【问题描述】:

我有一个 C# 控制台应用程序,它运行并将以下内容添加到 a 文件中:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
    <qf:VisualTemplate xmlns:qf="http://www.Qnomy.com/Templates" version="1.0" description="test doc">
      <qf:Styles />
      <qf:Parameters />
      <qf:SampleData />
      <qf:Design />
    </qf:VisualTemplate>

它使用这段代码来做到这一点:

        var doc = new XDocument(
            new XDeclaration("1.0", "utf-8", "yes"),
            new XElement(ns + "VisualTemplate",
                new XAttribute(XNamespace.Xmlns + "qf", url),
                new XAttribute("version", "1.0"),
                new XAttribute("description", "test doc"),
                    new XElement(ns + "Styles"),
                    new XElement(ns + "Parameters"),
                    new XElement(ns + "SampleData"),
                     new XElement(ns + "Design")
            )
        );

我还需要在 qf:Design 节点之间添加一个嵌入式 xsl 样式表,如下所示:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<qf:VisualTemplate xmlns:qf="http://www.Qnomy.com/Templates" version="1.0" description="test doc">
  <qf:Styles />
  <qf:Parameters />
  <qf:SampleData />
  <qf:Design>
     <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
       </xsl:stylesheet>
  </qf:Design>
</qf:VisualTemplate>

我尝试过以与创建 xml 相同的方式进行操作,但我不能使用 xsl 作为命名空间:

    var url2 = "http://www.w3.org/1999/XSL/Transform";

    var ns2 = XNamespace.Get(url2);

    var d = doc.Descendants(ns + "Design").First();

    d.AddBeforeSelf(new XComment("Place your HTML elements here"));
    d.Add(
        new XElement(ns + "Design",
            new XElement(ns2 + "stylesheet",
                new XAttribute(XNamespace.Xmlns + "xsl", ""),
                new XAttribute("version", "1.0")
            )
        )
    );

有什么方法可以像添加 XML 元素一样用 C# 添加 xsl 样式表?

【问题讨论】:

    标签: c# xml xslt


    【解决方案1】:

    根据您预期的输出 XML,xsl 前缀应该绑定到 "http://www.w3.org/1999/XSL/Transform",而不是空字符串:

    .....
    new XElement(ns2 + "stylesheet",
        new XAttribute(XNamespace.Xmlns + "xsl", "http://www.w3.org/1999/XSL/Transform"),
        new XAttribute("version", "1.0")
    )
    .....
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-20
      • 1970-01-01
      • 2012-11-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多