忽略doctype DTD但将其保留在转换后的XML C#中

时间:2015-04-20 08:23:14

标签: c# .net xml xslt transform

我需要转换标题中包含此doctype的XML文件:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE DOC SYSTEM "ts.dtd">
<?xml-stylesheet type="text/css" href="ts.css"?>

转换正常但是在XSL转换后doctype已经消失了,我已经在XmlReaderSettings上尝试了各种设置,但无法使其正常工作。

这是我的代码:

XslCompiledTransform xctTransformer = new XslCompiledTransform();
xctTransformer.Load(fiXSL.FullName);

XmlReaderSettings xrsReaderSettings = new XmlReaderSettings();
xrsReaderSettings.ConformanceLevel = ConformanceLevel.Document;
xrsReaderSettings.DtdProcessing = DtdProcessing.Ignore;
xrsReaderSettings.XmlResolver = null;
xrsReaderSettings.CloseInput = true;
xrsReaderSettings.IgnoreWhitespace = false;

XmlWriterSettings xwsWriterSettings = new XmlWriterSettings();
xwsWriterSettings.Indent = true;

XmlReader xrReader = XmlReader.Create(fiXML.FullName, xrsReaderSettings);
XmlWriter xwWriter = XmlWriter.Create(fiXML.FullName.Substring(0, fiXML.FullName.Length - 4) + "_TRANS.xml", xwsWriterSettings);

// Transform the XML using the XSL
xctTransformer.Transform(xrReader, xwWriter);
xctTransformer = null;

// Close reader + writer
xrReader.Close();
xwWriter.Close();

2 个答案:

答案 0 :(得分:1)

DOCTYPE节点不是XSLT / XPath数据模型的一部分,因此您无法使用XSLT处理和复制它。如果您希望最终结果具有某个DOCTYPE声明,那么使用XSLT的唯一方法是确保样式表中xsl:output包含doctype-system="ts.dtd"

答案 1 :(得分:0)

我刚发现的另一个答案是通过XSL以文本方式添加它:

<xsl:template match="/">
    <xsl:text disable-output-escaping='yes'>&lt;!DOCTYPE DOC SYSTEM "ts.dtd"&gt;</xsl:text>
    <xsl:copy>
        <xsl:apply-templates select = "*|@*|comment()|processing-instruction()|text()"/>
    </xsl:copy>
</xsl:template>