现在的位置: 首页 > 综合 > 正文

c#中如何在xml中添加和替换xsl样式表

2013年07月23日 ⁄ 综合 ⁄ 共 926字 ⁄ 字号 评论关闭

在xml文件中,如果要引入样式表xsl,就必须有这样一句:<?xml-stylesheet type="text/xsl" href="sample.xsl"?>

如果我们要用c#来添加样式表,那么方法如下:

            XmlDocument doc = new XmlDocument();
            doc.Load(xmlFile);

            // Add xsl style to the .xml
            XmlProcessingInstruction xmlXsl = doc.CreateProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" href=\"sample.xsl\""); //调用CreateProcessingInstruction方法
            doc.AppendChild(xmlXsl);
 

    doc.Save(xmlFile);

如果我们要对xml中已有的样式表进行替换,那么可以采用如下方法:

            XmlDocument doc = new XmlDocument();
            doc.Load(xmlFile);
            XmlNode xmlNode = doc.SelectSingleNode("/processing-instruction('xml-stylesheet')"); //Select the old stylesheet
            //Replace xsl stylesheet to the .xml 

            XmlProcessingInstruction xmlXsl = doc.CreateProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" href=\"newstyle.xsl\"");
            doc.ReplaceChild(xmlXsl, xmlNode); //调用replacechild方法来用新样式表替换旧样式
            doc.Save(xmlFile);

抱歉!评论已关闭.