我的网站项目中有一个 xml 文件和一个 xslt 文件。
xml文件:
<root>
<employee>
<firstname>Kaushal</firstname>
<lastname>Parik</lastname>
</employee>
<employee>
<firstname>Abhishek</firstname>
<lastname>Swarnkar</lastname>
</employee>
</root>
xslt:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl" xmlns:Concat="urn:XslSample">
<xsl:output method="html" indent="yes"/>
<xsl:template match="root">
<xsl:for-each select="employee">
<![CDATA[Concatenated name is ]]>
<xsl:value-of select="Concat:GetFullName(firstname,lastname)"/>
<xsl:value-of select="age"/>
<br />
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
aspx.cs:
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Xml.XPath;
using System.Xml.Xsl;
using System.Xml;
using System.IO;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
try
{
MemoryStream objStream = new MemoryStream();
StreamWriter objWriter = new StreamWriter(objStream, System.Text.Encoding.UTF8);
XPathDocument doc = new XPathDocument(Server.MapPath("XMLFile.xml"));
XslCompiledTransform trans = new XslCompiledTransform();
trans.Load(Server.MapPath("XSLTFile.xslt"));
//create the XslArgumentList and new BookUtils object
XsltArgumentList argList = new XsltArgumentList();
Concat objUtil = new Concat();
//this tells the argumentlist about BookUtils
argList.AddExtensionObject("urn:XslSample", objUtil);
//new XPathNavigator
XPathNavigator nav = doc.CreateNavigator();
//do the transform
trans.Transform(nav, argList, objWriter);
//objWriter.Flush();
objStream.Position = 0;
StreamReader oReader = new StreamReader(objStream);
string strResult = oReader.ReadToEnd();
//objWriter.Close();
//oReader.Close();
Response.Write(strResult);
}
catch (Exception Ex)
{ Response.Write(Ex.Message); }
}
}
public class Concat
{
public Concat()
{ }
public string GetFullName(string firstname, string lastname)
{ return "Mr." + firstname; }
}
当我运行该站点时,我需要从 xslt 调用 ac# 函数并更改 xml 文件中的值......我通过 ac# 代码在每个名字前面添加一个文本(比如“先生”)...... . 添加后将输出写为响应,但原xml没有修改。我希望将其反映在 xml 文件中....
需要xml输出:
<root>
<employee>
<firstname>Mr.Kaushal</firstname>
<lastname>Parik</lastname>
</employee>
<employee>
<firstname>Mr.Abhishek</firstname>
<lastname>Swarnkar</lastname>
</employee>
</root>
此外,作为下一步,我需要通过另一个 c# 函数在 xml 文件中添加另一个节点(比如年龄)......请注意,应该从我的 xslt 文件中调用 c# 函数......谁能帮助我有一个简单的代码????
最终需要的 xml:
<root>
<employee>
<firstname>Mr.Kaushal</firstname>
<lastname>Parik</lastname>
<age>34</age>
</employee>
<employee>
<firstname>Mr.Abhishek</firstname>
<lastname>Swarnkar</lastname>
<age>30</age>
</employee>
</root>